// Prodz — Network: explore & follow (no chat here). Two zones:
//  · "Le tue liste" — people you follow, grouped into lists. Auto by city and
//    by role; plus custom lists the user can create.
//  · "Da conoscere" — suggestions, CTA Follow
function Network() {
  const { L } = useL();
  const nav = useNav();
  const { Avatar, Button, Tabs } = window.ProdzDesignSystem_d0b87b;
  const [zone, setZone] = useStateS('people');
  const [following, setFollowing] = useStateS({});

  // people you follow → everyone in the directory except yourself
  const FOLLOWED = Object.keys(PEOPLE).filter((id) => id !== 'me');

  const [basis, setBasis] = useStateS('city');           // auto-group: city | role
  const [customLists, setCustomLists] = useStateS(() => ([
    { id: 'cl1', name: { it: 'Team Collezione Noir', en: 'Collezione Noir team' }, members: ['sofia', 'nina', 'elena'] },
    { id: 'cl2', name: { it: 'DP di fiducia', en: 'Trusted DPs' }, members: ['ale'] },
  ]));
  const [detail, setDetail] = useStateS(null);           // { title, icon, tint, members, custom }
  const [creating, setCreating] = useStateS(false);
  const [newName, setNewName] = useStateS('');
  const [newMembers, setNewMembers] = useStateS({});

  const listName = (n) => (typeof n === 'string' ? n : tr(L, n));

  const autoGroups = () => {
    const map = {};
    FOLLOWED.forEach((id) => {
      const p = PEOPLE[id];
      const key = basis === 'city' ? p.city : tr(L, p.role);
      (map[key] = map[key] || []).push(id);
    });
    return Object.entries(map).sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
  };

  const createList = () => {
    const members = Object.keys(newMembers).filter((k) => newMembers[k]);
    if (!newName.trim() || members.length === 0) return;
    setCustomLists((ls) => [{ id: 'cl' + Date.now(), name: newName.trim(), members }, ...ls]);
    setCreating(false); setNewName(''); setNewMembers({});
    nav.toast(L('Lista creata', 'List created'), null);
  };

  return (
    <div className="pz-screen-enter" style={{ paddingBottom: 28 }}>
      <TopBar />
      <div style={{ padding: '18px 16px 4px' }}>
        <h1 style={pageTitle}>Network</h1>
        <p style={pageSub}>{L('Esplora la rete e fai crescere i contatti.', 'Explore the network and grow your contacts.')}</p>
        <div style={{ marginTop: 14 }}>
          <Tabs value={zone} onChange={setZone}
            tabs={[{ id: 'people', label: L('Da conoscere', 'May know') }, { id: 'lists', label: L('Le tue liste', 'Your lists') }]} />
        </div>
      </div>

      {zone === 'lists' && (
        <div style={{ padding: '14px 16px 0' }}>
          <p style={{ ...pageSub, margin: '0 0 14px' }}>{L('Le persone che segui, raggruppate in liste.', 'The people you follow, grouped into lists.')}</p>

          {/* custom lists */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '0 0 12px' }}>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>{L('Personalizzate', 'Custom')}</span>
            <button onClick={() => setCreating(true)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'none', border: 'none', cursor: 'pointer', fontSize: 12.5, fontWeight: 700, color: 'var(--prodz-teal)' }}>
              <Ic n="Plus" s={15} color="var(--prodz-teal)" />{L('Nuova lista', 'New list')}
            </button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {customLists.map((cl) => (
              <ListCard key={cl.id} icon="Bookmark" tint="var(--prodz-gold)"
                name={listName(cl.name)} members={cl.members} Avatar={Avatar} L={L}
                onClick={() => setDetail({ title: listName(cl.name), icon: 'Bookmark', tint: 'var(--prodz-gold)', members: cl.members, custom: true })} />
            ))}
          </div>

          {/* auto-grouping basis */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '24px 0 12px' }}>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-subtle)' }}>{L('Automatiche', 'Automatic')}</span>
            <div style={{ display: 'inline-flex', gap: 6, padding: 3, borderRadius: 'var(--radius-pill)', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)' }}>
              {[{ id: 'city', label: L('Per città', 'By city'), icon: 'MapPin' }, { id: 'role', label: L('Per ruolo', 'By role'), icon: 'Briefcase' }].map((o) => (
                <button key={o.id} onClick={() => setBasis(o.id)} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6, height: 30, padding: '0 13px', borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer',
                  fontSize: 12.5, fontWeight: 700, whiteSpace: 'nowrap',
                  background: basis === o.id ? 'var(--prodz-teal)' : 'transparent',
                  color: basis === o.id ? 'var(--text-on-accent)' : 'var(--text-muted)',
                }}>
                  <Ic n={o.icon} s={14} color="currentColor" />{o.label}
                </button>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {autoGroups().map(([key, members]) => (
              <ListCard key={basis + key} icon={basis === 'city' ? 'MapPin' : 'Briefcase'} tint="var(--prodz-teal)"
                name={key} members={members} Avatar={Avatar} L={L}
                onClick={() => setDetail({ title: key, icon: basis === 'city' ? 'MapPin' : 'Briefcase', tint: 'var(--prodz-teal)', members, custom: false })} />
            ))}
          </div>
        </div>
      )}

      {/* list detail — members of a list */}
      <Sheet open={!!detail} onClose={() => setDetail(null)}>
        {detail && (
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Ic n={detail.icon} s={18} color={detail.tint} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-primary)' }}>{detail.title}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{detail.members.length} {detail.members.length === 1 ? L('persona', 'person') : L('persone', 'people')}{detail.custom ? '' : L(' · automatica', ' · automatic')}</div>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 360, overflowY: 'auto' }}>
              {detail.members.map((id) => {
                const p = PEOPLE[id];
                return (
                  <button key={id} onClick={() => { setDetail(null); nav.openProfile(id); }} style={listMemberRow}>
                    <Avatar src={p.avatar} alt={p.name} size={42} ring={p.ring} status={p.online ? 'online' : null} />
                    <span style={{ flex: 1, textAlign: 'left' }}>
                      <span style={{ display: 'block', fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{p.name}</span>
                      <span style={{ display: 'block', fontSize: 12, color: 'var(--text-muted)' }}>{tr(L, p.role)} · {p.city}</span>
                    </span>
                    <Ic n="ChevronRight" s={18} color="var(--text-subtle)" />
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </Sheet>

      {/* create custom list */}
      <Sheet open={creating} onClose={() => setCreating(false)}>
        <Eyebrow color="var(--prodz-gold)" style={{ marginBottom: 8 }}>{L('Nuova lista', 'New list')}</Eyebrow>
        <input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder={L('Nome della lista…', 'List name…')}
          style={{ width: '100%', height: 46, padding: '0 14px', borderRadius: 'var(--radius-md)', border: 'none', outline: 'none', background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', color: 'var(--text-body)', fontSize: 15, fontWeight: 600, fontFamily: 'var(--font-ui)' }} />
        <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-subtle)', margin: '16px 0 10px' }}>{L('Aggiungi persone', 'Add people')}</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 7, maxHeight: 260, overflowY: 'auto' }}>
          {FOLLOWED.map((id) => {
            const p = PEOPLE[id];
            const on = !!newMembers[id];
            return (
              <button key={id} onClick={() => setNewMembers((m) => ({ ...m, [id]: !m[id] }))} style={{ ...listMemberRow, background: on ? 'var(--teal-surface)' : 'var(--surface-raised)', boxShadow: on ? 'var(--ring-teal)' : 'var(--ring-inset-hairline)' }}>
                <Avatar src={p.avatar} alt={p.name} size={38} ring={p.ring} />
                <span style={{ flex: 1, textAlign: 'left' }}>
                  <span style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: 'var(--text-primary)' }}>{p.name}</span>
                  <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-muted)' }}>{tr(L, p.role)} · {p.city}</span>
                </span>
                <span style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: on ? 'var(--prodz-teal)' : 'transparent', boxShadow: on ? 'none' : 'inset 0 0 0 1.5px var(--border-strong)' }}>
                  {on && <Ic n="Check" s={14} color="var(--text-on-accent)" />}
                </span>
              </button>
            );
          })}
        </div>
        <div style={{ marginTop: 16 }}>
          <Button variant="primary" glow fullWidth leadingIcon={<Ic n="Plus" s={16} />} onClick={createList}>{L('Crea lista', 'Create list')}</Button>
        </div>
      </Sheet>

      {zone === 'people' && (
        <div style={{ padding: '8px 16px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {SUGGESTIONS.map((id) => {
            const p = PEOPLE[id];
            const isFollowing = !!following[id];
            const stats = { prods: ((id.length * 3) % 9) + 2, threads: ((id.length * 2) % 6) + 1, jobs: (id.length % 3) };
            return (
              <div key={id} style={personCard}>
                <button onClick={() => nav.openProfile(id)} style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'none', border: 'none', cursor: 'pointer', padding: 0, textAlign: 'left', width: '100%' }}>
                  <Avatar src={p.avatar} alt={p.name} size={52} ring={p.ring} status={p.online ? 'online' : null} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-primary)' }}>{p.name}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 1 }}>{tr(L, p.role)} · {p.city}</div>
                  </div>
                </button>
                {/* what's visible on a person card: produzioni, thread, job call */}
                <div style={{ display: 'flex', gap: 18, marginTop: 12, paddingLeft: 2 }}>
                  <MiniStat n={stats.prods} label={L('Produzioni', 'Prods')} />
                  <MiniStat n={stats.threads} label={L('Thread', 'Threads')} />
                  <MiniStat n={stats.jobs} label={L('Job call', 'Job calls')} />
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
                  <Button variant={isFollowing ? 'secondary' : 'primary'} size="sm" fullWidth
                    leadingIcon={<Ic n={isFollowing ? 'Check' : 'UserPlus'} s={15} />}
                    onClick={() => setFollowing((f) => ({ ...f, [id]: !f[id] }))}>
                    {isFollowing ? L('Segui già', 'Following') : L('Segui', 'Follow')}
                  </Button>
                  <Button variant="secondary" size="sm" fullWidth leadingIcon={<Ic n="Handshake" s={15} />}
                    onClick={() => nav.sendCollab(p)}>
                    {L('Collab', 'Collab')}
                  </Button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// A list card: leading icon, name + count, stacked member avatars.
function ListCard({ icon, tint, name, members, onClick, Avatar, L }) {
  const shown = members.slice(0, 4);
  return (
    <button onClick={onClick} style={listCard}>
      <span style={{ width: 40, height: 40, borderRadius: 12, flexShrink: 0, background: 'var(--surface-raised)', boxShadow: 'var(--ring-inset-hairline)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic n={icon} s={18} color={tint} />
      </span>
      <span style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
        <span style={{ display: 'block', fontSize: 14.5, fontWeight: 700, color: 'var(--text-primary)' }}>{name}</span>
        <span style={{ display: 'block', fontSize: 12, color: 'var(--text-muted)', marginTop: 1 }}>{members.length} {members.length === 1 ? L('persona', 'person') : L('persone', 'people')}</span>
      </span>
      <span style={{ display: 'flex', flexShrink: 0 }}>
        {shown.map((id, i) => {
          const p = PEOPLE[id];
          return (
            <span key={id} style={{ marginLeft: i === 0 ? 0 : -10, borderRadius: '50%', boxShadow: '0 0 0 2px var(--surface-card)' }}>
              <Avatar src={p.avatar} alt={p.name} size={28} ring="none" />
            </span>
          );
        })}
        {members.length > 4 && (
          <span style={{ marginLeft: -10, width: 28, height: 28, borderRadius: '50%', background: 'var(--surface-raised)', boxShadow: '0 0 0 2px var(--surface-card)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10.5, fontWeight: 700, color: 'var(--text-muted)' }}>+{members.length - 4}</span>
        )}
      </span>
      <Ic n="ChevronRight" s={18} color="var(--text-subtle)" />
    </button>
  );
}

function MiniStat({ n, label }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1 }}>{n}</span>
      <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--text-subtle)', marginTop: 3 }}>{label}</span>
    </div>
  );
}

const pageTitle = { margin: 0, fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 800, letterSpacing: '-0.03em', color: 'var(--text-primary)' };
const pageSub = { margin: '4px 0 0', fontSize: 13, color: 'var(--text-muted)' };
const activityRow = { display: 'flex', alignItems: 'center', gap: 12, padding: '12px 4px', background: 'none', border: 'none', borderBottom: '1px solid var(--border-hairline)', cursor: 'pointer', textAlign: 'left', width: '100%' };
const personCard = { background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--ring-inset-hairline)', padding: 16 };
const listCard = { display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '12px 14px', background: 'var(--surface-card)', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--ring-inset-hairline)' };
const listMemberRow = { display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: 10, background: 'var(--surface-raised)', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-md)' };

Object.assign(window, { Network, ListCard, MiniStat, pageTitle, pageSub });
