// WealthIntelligence — Profile page (inactivity + temporary illness + mailboxes)
const ProfilePage = ({state, t, updateState, setTemporaryIllness, openUserEditor}) => {
  const inactivity = state.inactivity;
  const ti = state.temporaryIllness || { active:false, since:null, note:'' };

  const [tiNote, setTiNote] = useState(ti.note || '');
  useEffect(()=>{ setTiNote(ti.note || ''); }, [ti.note]);

  const cassettePermanent = state.cassette.filter(c => c.trigger==='permanent');
  const cassetteTemporary = state.cassette.filter(c => c.trigger==='temporary');

  const fmtSince = (iso) => {
    if (!iso) return '';
    try { return new Date(iso).toLocaleString('it-IT', { day:'numeric', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' }); }
    catch(e){ return iso; }
  };

  return <div className="fade-in">
    <PageHeader
      eyebrow={t.profile.title}
      title={t.profile.hero}
      subtitle={t.profile.sub}
    />

    <div style={{display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:32}}>
      <div style={{display:'flex', flexDirection:'column', gap:20}}>

        {/* Inactivity — drives permanent triggers */}
        <div className="card" style={{padding:28}}>
          <div className="row" style={{marginBottom:8, gap:12}}>
            <span style={{
              width:36, height:36, borderRadius:10, background:'var(--trigger-permanent-soft)',
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              color:'var(--trigger-permanent)',
            }}><Icon name="clock" size={18}/></span>
            <div className="grow">
              <h3 style={{margin:0, fontSize:18, fontWeight:600}}>{t.profile.section_inactivity}</h3>
              <div style={{fontSize:12, color:'var(--trigger-permanent)', marginTop:2, fontWeight:500}}>{t.profile.inactivity_drives}</div>
            </div>
            <label className="toggle">
              <button className={inactivity.enabled?'on':''} onClick={()=>updateState(s=>({...s, inactivity:{...s.inactivity, enabled:true}}))}>ON</button>
              <button className={!inactivity.enabled?'on':''} onClick={()=>updateState(s=>({...s, inactivity:{...s.inactivity, enabled:false}}))}>OFF</button>
            </label>
          </div>
          <p className="muted" style={{margin:'8px 0 20px', fontSize:14, lineHeight:1.5}}>{t.profile.inactivity_desc}</p>

          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:18}}>
            <div className="card-paper" style={{padding:16, background:'var(--paper-2)', border:'1px solid var(--line)', borderRadius:10}}>
              <div className="t-eyebrow" style={{marginBottom:6}}>{t.profile.months}</div>
              <div className="row" style={{gap:12, alignItems:'baseline'}}>
                <div className="t-num" style={{fontSize:42, lineHeight:1}}>{inactivity.months}</div>
                <div className="row" style={{gap:4}}>
                  <button className="btn btn-ghost btn-icon" onClick={()=>updateState(s=>({...s, inactivity:{...s.inactivity, months:Math.max(1,s.inactivity.months-1)}}))}>−</button>
                  <button className="btn btn-ghost btn-icon" onClick={()=>updateState(s=>({...s, inactivity:{...s.inactivity, months:Math.min(24,s.inactivity.months+1)}}))}>+</button>
                </div>
              </div>
            </div>
            <div className="card-paper" style={{padding:16, background:'var(--paper-2)', border:'1px solid var(--line)', borderRadius:10}}>
              <div className="t-eyebrow" style={{marginBottom:6}}>{t.profile.pings}</div>
              <div className="row" style={{gap:12, alignItems:'baseline'}}>
                <div className="t-num" style={{fontSize:42, lineHeight:1}}>{inactivity.pingCount}</div>
                <div className="row" style={{gap:4}}>
                  <button className="btn btn-ghost btn-icon" onClick={()=>updateState(s=>({...s, inactivity:{...s.inactivity, pingCount:Math.max(1,s.inactivity.pingCount-1)}}))}>−</button>
                  <button className="btn btn-ghost btn-icon" onClick={()=>updateState(s=>({...s, inactivity:{...s.inactivity, pingCount:Math.min(5,s.inactivity.pingCount+1)}}))}>+</button>
                </div>
              </div>
            </div>
          </div>

          <div>
            <div className="t-eyebrow" style={{marginBottom:8}}>{t.profile.trusted_contacts}</div>
            <div style={{display:'flex', flexWrap:'wrap', gap:8}}>
              {(inactivity.trustedContacts||[]).map(pid => {
                const p = state.people.find(x=>x.id===pid); if (!p) return null;
                return <span key={pid} className="chip" style={{padding:'4px 12px 4px 4px'}}>
                  <Monogram color={p.color} initials={p.initials} size="sm"/>{p.name.split(' ')[0]}
                </span>;
              })}
            </div>
            <div className="muted" style={{fontSize:12, marginTop:10}}>
              Cassette che si attiveranno: <strong>{cassettePermanent.length}</strong>
            </div>
          </div>
        </div>

        {/* Temporary illness — manual trigger */}
        <div className="card" style={{
          padding:28,
          background: ti.active ? 'var(--trigger-temporary-soft)' : '#fff',
          borderColor: ti.active ? 'transparent' : 'var(--line)',
        }}>
          <div className="row" style={{marginBottom:8, gap:12}}>
            <span style={{
              width:36, height:36, borderRadius:10,
              background: ti.active ? '#fff' : 'var(--trigger-temporary-soft)',
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              color:'var(--trigger-temporary)',
            }}><Icon name="medkit" size={18}/></span>
            <div className="grow">
              <h3 style={{margin:0, fontSize:18, fontWeight:600}}>{t.profile.section_temporary}</h3>
              <div style={{fontSize:12, color:'var(--trigger-temporary)', marginTop:2, fontWeight:500}}>
                {ti.active ? `${t.profile.temporary_active} ${fmtSince(ti.since)}` : t.profile.temporary_inactive}
              </div>
            </div>
          </div>
          <p className="muted" style={{margin:'8px 0 18px', fontSize:14, lineHeight:1.5}}>{t.profile.temporary_desc}</p>

          <div style={{marginBottom:16}}>
            <div className="t-eyebrow" style={{marginBottom:6}}>{t.profile.temporary_note}</div>
            <textarea className="input" rows={2} placeholder={t.profile.temporary_note_ph}
                      value={tiNote} onChange={e=>setTiNote(e.target.value)}
                      disabled={ti.active}
                      style={{resize:'vertical', fontFamily:'inherit', background: ti.active?'var(--paper-2)':'#fff'}}/>
          </div>

          <div className="row" style={{gap:12, justifyContent:'space-between', flexWrap:'wrap'}}>
            <div className="muted" style={{fontSize:12}}>
              Cassette che diventeranno accessibili: <strong>{cassetteTemporary.length}</strong>
            </div>
            {ti.active ? (
              <button className="btn btn-secondary" style={{background:'#fff'}} onClick={()=>setTemporaryIllness(false)}>
                <Icon name="check" size={14}/>{t.profile.temporary_deactivate}
              </button>
            ) : (
              <button className="btn btn-warn" onClick={()=>setTemporaryIllness(true, tiNote)}>
                <Icon name="medkit" size={14}/>{t.profile.temporary_activate}
              </button>
            )}
          </div>
        </div>

        {/* Mailboxes */}
        <div className="card" style={{padding:28}}>
          <div className="row" style={{marginBottom:18, gap:12}}>
            <Icon name="mail" size={20}/>
            <h3 style={{margin:0, fontSize:18, fontWeight:600}}>{t.profile.section_mailboxes}</h3>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:10}}>
            {state.mailboxes.map(m => (
              <div key={m.id} className="row" style={{padding:14, border:'1px solid var(--line)', borderRadius:10, gap:14}}>
                <span style={{width:36, height:36, borderRadius:8, background:m.kind==='google'?'#F2E9DA':m.kind==='apple'?'#E4F1F4':'#E2E9EA', display:'inline-flex', alignItems:'center', justifyContent:'center', fontWeight:600, fontSize:14}}>
                  {m.kind==='google'?'G':m.kind==='apple'?'':'M'}
                </span>
                <div className="grow">
                  <div style={{fontWeight:500, fontSize:14}}>{m.email || (m.kind==='microsoft'?'Microsoft':'')}</div>
                  <div className="muted" style={{fontSize:12}}>
                    {m.connected ? `Ultimo scan ${m.lastScan} · ${m.servicesFound} servizi` : 'Non connessa'}
                  </div>
                </div>
                {m.connected
                  ? <span className="chip chip-accent" style={{gap:6}}><span style={{width:6,height:6,borderRadius:'50%',background:'var(--olive-500)'}}/>Attiva</span>
                  : <button className="btn btn-secondary btn-sm">Connetti</button>}
              </div>
            ))}
            <button className="btn btn-ghost" style={{justifyContent:'center', padding:'12px', border:'1px dashed var(--line-strong)', borderRadius:10}}>
              <Icon name="plus" size={16}/>{t.profile.add_mailbox}
            </button>
          </div>
        </div>
      </div>

      {/* Right column: user card */}
      <div style={{display:'flex', flexDirection:'column', gap:20}}>
        <div className="card" style={{padding:28, textAlign:'center'}}>
          <Monogram name={state.user.name} color={state.user.color} initials={state.user.initials} size="xl"/>
          <h3 style={{margin:'16px 0 4px', fontFamily:'var(--f-serif)', fontStyle:'italic', fontWeight:400, fontSize:22}}>{state.user.name}</h3>
          <div className="muted" style={{fontSize:13}}>{state.user.email}</div>
          {state.user.phone && <div className="muted" style={{fontSize:13}}>{state.user.phone}</div>}
          <div style={{marginTop:18}}>
            <button className="btn btn-secondary btn-sm" onClick={openUserEditor}><Icon name="edit" size={13}/>Modifica dati</button>
          </div>
        </div>

        {/* Trigger summary */}
        <div className="card" style={{padding:24}}>
          <div className="t-eyebrow" style={{marginBottom:14}}>Riepilogo trigger</div>

          <div style={{padding:'12px 0', borderBottom:'1px solid var(--line)'}}>
            <div className="row" style={{gap:10, marginBottom:6}}>
              <span className="trigger-dot permanent"/>
              <span style={{fontSize:13, fontWeight:500}}>{t.vault.triggers.permanent}</span>
            </div>
            <div className="muted" style={{fontSize:12, lineHeight:1.4}}>
              Automatico via inattività ({inactivity.months} mesi · {inactivity.pingCount} ping). {cassettePermanent.length} cassette.
            </div>
          </div>

          <div style={{padding:'12px 0'}}>
            <div className="row" style={{gap:10, marginBottom:6}}>
              <span className="trigger-dot temporary"/>
              <span style={{fontSize:13, fontWeight:500}}>{t.vault.triggers.temporary}</span>
            </div>
            <div className="muted" style={{fontSize:12, lineHeight:1.4}}>
              Manuale. {ti.active ? <span style={{color:'var(--trigger-temporary)', fontWeight:500}}>Attiva ora.</span> : 'Non attiva.'} {cassetteTemporary.length} cassette.
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>;
};

// ------- User editor (drawer) -------
const UserEditor = ({user, t, onClose, onSave}) => {
  const computeInitials = (name) => (name||'').split(/\s+/).filter(Boolean).map(w => w[0]).join('').slice(0,2).toUpperCase();
  const [draft, setDraft] = useState(() => ({
    name: user.name || '',
    email: user.email || '',
    phone: user.phone || '',
    color: user.color || '#173B3F',
    initials: user.initials || computeInitials(user.name || ''),
  }));

  const set = (k, v) => setDraft(d => {
    const next = {...d, [k]:v};
    if (k === 'name') next.initials = computeInitials(v);
    return next;
  });

  const valid = draft.name.trim().length > 0;

  return <>
    <div className="backdrop" onClick={onClose}/>
    <div className="drawer fade-in">
      <DialogHeader title="Modifica i tuoi dati" onClose={onClose}/>

      <div style={{padding:24}}>

        {/* Live preview */}
        <div className="row" style={{gap:16, marginBottom:24, alignItems:'center'}}>
          <Monogram color={draft.color} initials={draft.initials || '·'} size="xl"/>
          <div>
            <div style={{fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:24, lineHeight:1.1}}>{draft.name || 'Il tuo nome'}</div>
            <div className="muted" style={{fontSize:13, marginTop:4}}>{draft.email || 'email@esempio.it'}</div>
          </div>
        </div>

        <Field label="Nome e cognome">
          <input className="input" placeholder="Es. Mario Rossi"
                 value={draft.name} onChange={e=>set('name', e.target.value)}/>
        </Field>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
          <Field label="Email">
            <input className="input" type="email" placeholder="mario@rossi.it"
                   value={draft.email} onChange={e=>set('email', e.target.value)}/>
          </Field>

          <Field label="Telefono">
            <input className="input" type="tel" placeholder="+39 333 412 7785"
                   value={draft.phone} onChange={e=>set('phone', e.target.value)}/>
          </Field>
        </div>

        <Field label="Colore monogramma" help="Le iniziali vengono generate automaticamente dal nome.">
          <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
            {window.WI.COLOR_OPTIONS.map(co => (
              <button key={co} type="button" onClick={()=>set('color', co)}
                style={{
                  width:32, height:32, borderRadius:'50%',
                  border:'2px solid '+(draft.color===co ? 'var(--ink)' : 'transparent'),
                  background:co, cursor:'pointer',
                }} aria-label={co}/>
            ))}
          </div>
        </Field>
      </div>

      <div className="row" style={{
        position:'sticky', bottom:0, padding:'16px 24px', background:'var(--paper)',
        borderTop:'1px solid var(--line)', justifyContent:'flex-end', gap:10,
      }}>
        <button className="btn btn-ghost" onClick={onClose}>{t.common.cancel}</button>
        <button className="btn btn-primary" disabled={!valid} onClick={()=>onSave(draft)}>
          <Icon name="check" size={14}/>{t.common.save}
        </button>
      </div>
    </div>
  </>;
};

Object.assign(window, { ProfilePage, UserEditor });
