const FamilySettings = () => {
  const { user, family, parents, children, refresh } = useSession();
  const [addOpen, setAddOpen] = React.useState(false);
  const [inviteCopied, setInviteCopied] = React.useState(false);
  const [pwChildOpen, setPwChildOpen] = React.useState(null);
  const [pwFlash, setPwFlash] = React.useState('');
  const [authChildOpen, setAuthChildOpen] = React.useState(null); // { child, kind }

  const copyInvite = async () => {
    try {
      await navigator.clipboard.writeText(family.inviteCode);
      setInviteCopied(true);
      setTimeout(()=> setInviteCopied(false), 1500);
    } catch {}
  };

  const onChildAdded = async () => {
    await refresh();
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 20 }}>
      <header>
        <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.08em', textTransform:'uppercase', marginBottom: 6 }}>НАСТРОЙКИ</div>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 600, letterSpacing:'-.02em' }}>Семья</h1>
        <p style={{ color:'var(--fg-muted)', fontSize: 14, margin:'6px 0 0' }}>
          У ребёнка может быть несколько родителей. Все видят одни и те же данные.
        </p>
      </header>

      <Card>
        <SectionTitle
          eyebrow="ДЕТИ"
          title={`Дети · ${children.length}`}
          action={<Button variant="primary" size="sm" leading={<IconPlus size={14}/>} onClick={()=> setAddOpen(true)}>Добавить</Button>}
        />
        {children.length === 0 && (
          <div style={{ padding:'16px 0', color:'var(--fg-subtle)', fontSize: 13 }}>Пока нет ни одного ребёнка.</div>
        )}
        <div style={{ display:'flex', flexDirection:'column', gap: 2 }}>
          {children.map((c, i) => (
            <div key={c.id} style={{
              display:'flex', alignItems:'center', gap: 14, padding:'14px 4px',
              borderBottom: i < children.length-1 ? '1px solid var(--border)' : 'none'
            }}>
              <Avatar emoji={c.avatar} color={c.color} size={44} ring/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>{c.name}</div>
                <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.04em', textTransform:'uppercase', marginTop: 2 }}>
                  {c.age} лет · логин {c.login}
                </div>
              </div>
              <div style={{ display:'flex', gap: 4, flexWrap:'wrap' }}>
                <Button variant="ghost" size="sm" onClick={()=> setPwChildOpen(c)}>Пароль</Button>
                <Button variant="ghost" size="sm" onClick={()=> setAuthChildOpen({ child: c, kind: 'pattern' })}>
                  {c.hasPattern ? '✏️ Рисунок ✓' : '✏️ Рисунок'}
                </Button>
                <Button variant="ghost" size="sm" onClick={()=> setAuthChildOpen({ child: c, kind: 'emoji-pin' })}>
                  {c.hasEmojiPin ? '🙂 Эмодзи ✓' : '🙂 Эмодзи'}
                </Button>
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card>
        <SectionTitle eyebrow="РОДИТЕЛИ" title={`Взрослые · ${parents.length}`}/>
        <div style={{ display:'flex', flexDirection:'column', gap: 2 }}>
          {parents.map((p, i) => (
            <div key={p.id} style={{
              display:'flex', alignItems:'center', gap: 14, padding:'14px 4px',
              borderBottom: i < parents.length-1 ? '1px solid var(--border)' : 'none'
            }}>
              <Avatar emoji={p.avatar} color={p.color} size={44} ring/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display:'flex', alignItems:'center', gap: 8, flexWrap:'wrap' }}>
                  <span style={{ fontWeight: 600 }}>{p.name}</span>
                  {p.id === user?.id && <Pill tone="accent">ЭТО ВЫ</Pill>}
                </div>
                <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.04em', textTransform:'uppercase', marginTop: 2 }}>
                  {p.parentRole || 'Родитель'} · логин {p.login}
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card>
        <SectionTitle eyebrow="ПРИГЛАШЕНИЕ" title="Код семьи"/>
        <div style={{
          padding: 18, background:'var(--surface-2)', border:'2px dashed var(--border-strong)', borderRadius: 12,
          display:'flex', alignItems:'center', justifyContent:'space-between', gap: 14, flexWrap:'wrap'
        }}>
          <div>
            <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.08em', marginBottom: 6 }}>КОД</div>
            <div className="mono" style={{ fontSize: 24, fontWeight: 600, letterSpacing:'.1em' }}>{family?.inviteCode}</div>
          </div>
          <Button variant={inviteCopied ? 'soft' : 'primary'} onClick={copyInvite} leading={inviteCopied ? <IconCheck size={14}/> : null}>
            {inviteCopied ? 'Скопировано' : 'Скопировать'}
          </Button>
        </div>
        <div style={{ fontSize: 13, color:'var(--fg-muted)', marginTop: 10 }}>
          Поделитесь кодом с другим родителем — при регистрации он введёт этот код и окажется в той же семье.
        </div>
      </Card>

      <SecuritySection/>

      <AltLoginsSection/>

      <PushSubscriptionsSection/>

      <AddChildModal open={addOpen} onClose={()=> setAddOpen(false)} onAdded={onChildAdded}/>
      <ChangeChildPasswordModal
        open={!!pwChildOpen}
        child={pwChildOpen}
        onClose={()=> setPwChildOpen(null)}
        onSuccess={()=> { setPwFlash('Пароль ребёнка обновлён'); setTimeout(()=> setPwFlash(''), 2200); }}
      />
      <ChildAuthModal
        open={!!authChildOpen}
        child={authChildOpen?.child}
        kind={authChildOpen?.kind}
        onClose={()=> setAuthChildOpen(null)}
        onSaved={async ()=> { setAuthChildOpen(null); await refresh(); setPwFlash('Способ входа обновлён'); setTimeout(()=> setPwFlash(''), 2200); }}
      />
      {pwFlash && (
        <div style={{
          position:'fixed', bottom: 'calc(env(safe-area-inset-bottom, 0px) + 96px)',
          left:'50%', transform:'translateX(-50%)',
          padding:'10px 18px', borderRadius: 999, background:'var(--fg)', color:'#fff', fontSize: 13,
          boxShadow:'var(--shadow-md)', zIndex: 50, maxWidth:'90vw'
        }}>
          <IconCheck size={12} stroke={2.5}/> {pwFlash}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { FamilySettings });
