// Profile screen — personal account, appearance, notifications, connected calendars.
// Reads/writes window.Account (single-user); nav.refresh() re-renders the app.

const { FONT_DISPLAY: PF_DISPLAY, FONT_BODY: PF_BODY, FONT_MONO: PF_MONO } = window.HIFI;

// ---------- small local controls ----------
const PfToggle = ({ t, on, onChange }) => (
  <button onClick={() => onChange(!on)} style={{
    width: 42, height: 24, borderRadius: 999, border: 'none', cursor: 'pointer', padding: 2,
    background: on ? t.accent : t.border, transition: 'background 0.15s ease',
    display: 'flex', justifyContent: on ? 'flex-end' : 'flex-start', flex: '0 0 auto',
  }}>
    <span style={{ width: 20, height: 20, borderRadius: '50%', background: t.card, boxShadow: '0 1px 2px rgba(0,0,0,0.2)' }}/>
  </button>
);

const PfToggleRow = ({ t, label, sub, on, onChange, first }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 0', borderTop: first ? 'none' : `1px solid ${t.divider}` }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 14, color: t.ink, fontWeight: 500 }}>{label}</div>
      {sub && <div style={{ fontSize: 12, color: t.inkSoft, marginTop: 2 }}>{sub}</div>}
    </div>
    <PfToggle t={t} on={on} onChange={onChange}/>
  </div>
);

const SectionCard = ({ t, icon, title, sub, action, children }) => (
  <Card t={t} pad={20}>
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 16 }}>
      <div style={{ display: 'flex', gap: 11, alignItems: 'center' }}>
        {icon && (
          <span style={{ width: 30, height: 30, borderRadius: 8, background: t.inputBg, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.inkSoft, flex: '0 0 auto' }}>
            <HIcon kind={icon} size={16}/>
          </span>
        )}
        <div>
          <div style={{ fontSize: 14.5, fontWeight: 600, color: t.ink }}>{title}</div>
          {sub && <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 1 }}>{sub}</div>}
        </div>
      </div>
      {action}
    </div>
    {children}
  </Card>
);

// ============================================================
// Profile screen
// ============================================================
const HifiProfileScreen = ({ t, nav, themeId, onTheme }) => {
  const me = window.Account.current();

  // account form (local until saved)
  const [name, setName] = React.useState(me.name);
  const [email, setEmail] = React.useState(me.email);
  const [tz, setTz] = React.useState(me.tz);
  const [savedAt, setSavedAt] = React.useState(false);

  React.useEffect(() => { setName(me.name); setEmail(me.email); setTz(me.tz); }, [me.id]);

  const dirty = name !== me.name || email !== me.email || tz !== me.tz;
  const saveAccount = () => {
    const initial = (name.trim().charAt(0) || 'O').toUpperCase();
    window.Account.updateCurrent({ name, email, tz, initial });
    setSavedAt(true); setTimeout(() => setSavedAt(false), 1800);
    nav.refresh();
  };

  const setNotif = (key, val) => { window.Account.updateCurrent({ notif: { ...me.notif, [key]: val } }); nav.refresh(); };

  const cals = me.calendar || {};
  const connectedCount = Object.keys(cals).length;

  return (
    <>
      <TopBar t={t}
        title="Profile"
        sub="Your account, appearance, notifications, and calendar connections"
      />

      <div style={{ padding: '20px 28px 40px', maxWidth: 860, display: 'flex', flexDirection: 'column', gap: 16 }}>

        {/* ---- Account ---- */}
        <SectionCard t={t} icon="user" title="Account" sub="Your name, sign-in email, password, and time zone">
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 20 }}>
            <Avatar t={t} member={me} size={60}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16, color: t.ink, fontWeight: 600 }}>{me.name || 'Owner'}</div>
              <div style={{ fontSize: 13, color: t.inkSoft, marginTop: 1 }}>{me.email || 'no email yet'}</div>
            </div>
            <Btn t={t}>Change photo</Btn>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <TextInput t={t} label="Full name" value={name} onChange={setName}/>
            <TextInput t={t} label="Sign-in email" value={email} onChange={setEmail} type="email"/>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14, alignItems: 'end' }}>
            <div>
              <div style={{ fontSize: 12, color: t.inkSoft, marginBottom: 5, fontWeight: 500 }}>Password</div>
              <div style={{ display: 'flex', gap: 8 }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', padding: '9px 12px', background: t.inputBg, border: `1px solid ${t.border}`, borderRadius: 9, fontFamily: PF_MONO, fontSize: 16, letterSpacing: 2, color: t.inkSoft }}>••••••••••</div>
                <Btn t={t} onClick={() => nav.openModal('password')}>Change</Btn>
              </div>
            </div>
            <SelectInput t={t} label="Time zone" value={tz} onChange={setTz} options={TZ_OPTIONS}/>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 18 }}>
            <Btn t={t} primary onClick={saveAccount} style={dirty ? {} : { opacity: 0.55, pointerEvents: 'none' }}>Save changes</Btn>
            {savedAt && <span style={{ fontSize: 13, color: t.ok, display: 'flex', alignItems: 'center', gap: 5 }}><HIcon kind="check" size={14}/> Saved</span>}
            {dirty && !savedAt && <span style={{ fontSize: 13, color: t.inkFaint }}>Unsaved changes</span>}
          </div>
        </SectionCard>

        {/* ---- Connected calendars ---- */}
        <SectionCard t={t} icon="cal" title="Connected calendars"
          sub="Push routine reminders out to a calendar you already check"
          action={<Pill t={t} color={t.ok} bg={t.okBg}><HIcon kind="sync" size={12}/> {connectedCount} connected</Pill>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {CAL_PROVIDERS.map(p => {
              const conn = cals[p.id];
              return (
                <div key={p.id} style={{
                  display: 'flex', alignItems: 'center', gap: 13,
                  padding: '13px 14px', border: `1px solid ${conn ? t.border : t.divider}`,
                  borderRadius: 11, background: conn ? t.card : t.paper,
                }}>
                  <span style={{ width: 38, height: 38, borderRadius: 9, background: conn ? p.tint : t.inputBg, color: conn ? '#fff' : t.inkFaint, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto', border: conn ? 'none' : `1px solid ${t.border}` }}>
                    <HIcon kind="cal" size={18}/>
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: t.ink }}>{p.name}</div>
                    {conn ? (
                      <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {conn.account} · {conn.direction === 'two-way' ? 'Two-way' : 'One-way'} · {conn.scope} · {conn.lead}
                      </div>
                    ) : (
                      <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 1 }}>{p.sub}</div>
                    )}
                  </div>
                  {conn ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto' }}>
                      <Pill t={t} color={t.ok} bg={t.okBg}><StatusDot color={t.ok}/> Synced {conn.last}</Pill>
                      <Btn t={t} onClick={() => nav.openModal('calendar', { provider: p.id, conn })}>Configure</Btn>
                      <Btn t={t} danger onClick={() => { window.Account.setCalendar(p.id, null); nav.refresh(); }}>Disconnect</Btn>
                    </div>
                  ) : (
                    <Btn t={t} primary onClick={() => nav.openModal('calendar', { provider: p.id })}><HIcon kind="link" size={14}/> Connect</Btn>
                  )}
                </div>
              );
            })}
          </div>
          <div style={{ fontSize: 12.5, color: t.inkFaint, marginTop: 13, display: 'flex', alignItems: 'center', gap: 6 }}>
            <HIcon kind="repeat" size={13}/> New and edited routines on the <TLink t={t} onClick={() => nav.go('routines')}>Routines</TLink> calendar sync automatically once connected.
          </div>
        </SectionCard>

        {/* ---- Appearance ---- */}
        <SectionCard t={t} icon="sun" title="Appearance" sub="The household photo and palette">
          <HeroPicker t={t}/>
          <div style={{ height: 1, background: t.divider, margin: '14px 0' }}/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '4px 2px' }}>
            <div style={{ display: 'flex', gap: 6, flex: '0 0 auto' }}>
              <span style={{ width: 26, height: 26, borderRadius: 7, background: t.accent }}/>
              <span style={{ width: 26, height: 26, borderRadius: 7, background: t.paper, border: `1px solid ${t.border}` }}/>
              <span style={{ width: 26, height: 26, borderRadius: 7, background: t.soon }}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, color: t.ink, fontWeight: 600 }}>{t.name}</div>
              <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 2, lineHeight: 1.4 }}>{t.blurb}</div>
            </div>
            <Pill t={t} color={t.accentDeep} bg={t.okBg}><HIcon kind="check" size={11}/> Active</Pill>
          </div>
        </SectionCard>

        {/* ---- Notifications ---- */}
        <SectionCard t={t} icon="bell" title="Notifications" sub="What the Hub tells you, and how">
          <div style={{ marginBottom: 6 }}>
            <SelectInput t={t} label="Delivery" value={me.notif.channel} onChange={v => setNotif('channel', v)} options={CHANNEL_OPTIONS}/>
          </div>
          <PfToggleRow t={t} label="Overdue reminders" sub="When a routine becomes overdue" on={me.notif.overdue} onChange={v => setNotif('overdue', v)} first/>
          <PfToggleRow t={t} label="Routine reminders" sub="‘X weeks before’ reminders set on individual routines" on={!!me.notif.reminders} onChange={v => setNotif('reminders', v)}/>
          <PfToggleRow t={t} label="Due-soon digest" sub="Weekly summary of what's coming up" on={me.notif.digest} onChange={v => setNotif('digest', v)}/>
          <PfToggleRow t={t} label="Info-gap nudges" sub="Remind me to fill in missing make / model details" on={me.notif.gaps} onChange={v => setNotif('gaps', v)}/>
        </SectionCard>

        {/* ---- Session ---- */}
        <SectionCard t={t} icon="user" title="Session" sub="Signed in via magic link">
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, color: t.ink }}>
                {window.Cloud && window.Cloud.currentUser && window.Cloud.currentUser()
                  ? window.Cloud.currentUser().email
                  : 'Not signed in'}
              </div>
              <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 2 }}>
                Signing out clears local data on this device. Your cloud data is kept.
              </div>
            </div>
            <Btn t={t} danger onClick={() => { if (window.signOutOfHub) window.signOutOfHub(); }}>
              Sign out
            </Btn>
          </div>
        </SectionCard>

      </div>
    </>
  );
};

// ============================================================
// Change-password modal
// ============================================================
const HifiPasswordModal = ({ t, nav }) => {
  const [cur, setCur] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [show, setShow] = React.useState(false);
  const ok = pw.length >= 8 && pw === confirm && cur.length > 0;
  const mismatch = confirm.length > 0 && pw !== confirm;

  return (
    <PfModalShell t={t} title="Change password" sub="Use at least 8 characters" onClose={() => nav.closeOverlays()} width={440}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        <PwField t={t} label="Current password" value={cur} onChange={setCur} show={show}/>
        <PwField t={t} label="New password" value={pw} onChange={setPw} show={show}/>
        <PwField t={t} label="Confirm new password" value={confirm} onChange={setConfirm} show={show} error={mismatch ? "Passwords don't match" : null}/>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: t.inkSoft, cursor: 'pointer' }}>
          <input type="checkbox" checked={show} onChange={e => setShow(e.target.checked)} style={{ accentColor: t.accent, width: 15, height: 15 }}/>
          Show passwords
        </label>
      </div>
      <PfModalFooter t={t}>
        <Btn t={t} onClick={() => nav.closeOverlays()}>Cancel</Btn>
        <Btn t={t} primary onClick={() => nav.closeOverlays()} style={ok ? {} : { opacity: 0.55, pointerEvents: 'none' }}>Update password</Btn>
      </PfModalFooter>
    </PfModalShell>
  );
};

const PwField = ({ t, label, value, onChange, show, error }) => {
  const [f, setF] = React.useState(false);
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontSize: 12, color: t.inkSoft, marginBottom: 5, fontWeight: 500 }}>{label}</div>
      <input type={show ? 'text' : 'password'} value={value} onChange={e => onChange(e.target.value)}
        onFocus={() => setF(true)} onBlur={() => setF(false)}
        style={{
          width: '100%', boxSizing: 'border-box', padding: '9px 12px',
          background: t.inputBg, border: `1px solid ${error ? t.overdue : (f ? t.accent : t.border)}`,
          borderRadius: 9, fontSize: 14, color: t.ink, fontFamily: PF_BODY, outline: 'none',
          boxShadow: f && !error ? `0 0 0 3px ${t.okBg}` : 'none',
        }}/>
      {error && <div style={{ fontSize: 12, color: t.overdue, marginTop: 4 }}>{error}</div>}
    </label>
  );
};

// ============================================================
// Connect / configure calendar modal
// ============================================================
const HifiCalendarModal = ({ t, nav, ctx }) => {
  const provider = CAL_PROVIDERS.find(p => p.id === ctx.provider) || CAL_PROVIDERS[0];
  const existing = ctx.conn || {};
  const me = window.Account.current();
  const [account, setAccount] = React.useState(existing.account || me.email);
  const [target, setTarget] = React.useState(existing.target || 'Kingsleigh Home');
  const [scope, setScope] = React.useState(existing.scope || 'All routines');
  const [direction, setDirection] = React.useState(existing.direction || 'two-way');
  const [lead, setLead] = React.useState(existing.lead || '1 day before');

  const save = () => {
    window.Account.setCalendar(provider.id, {
      connected: true, account, target, scope, direction, lead,
      last: existing.last || 'Just now',
    });
    nav.refresh(); nav.closeOverlays();
  };

  return (
    <PfModalShell t={t}
      title={`${ctx.conn ? 'Configure' : 'Connect'} ${provider.name}`}
      sub="Choose what syncs from your Routines calendar"
      onClose={() => nav.closeOverlays()} width={480}
      icon={<span style={{ width: 34, height: 34, borderRadius: 9, background: provider.tint, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><HIcon kind="cal" size={17}/></span>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <TextInput t={t} label={`${provider.name} account`} value={account} onChange={setAccount} type="email"/>
        <TextInput t={t} label="Target calendar" value={target} onChange={setTarget} placeholder="Calendar name"/>
        <SelectInput t={t} label="What to sync" value={scope} onChange={setScope}
          options={['All routines', 'Only routines assigned to me', 'Owner-only routines', 'Selected categories…']}/>
        <div>
          <div style={{ fontSize: 12, color: t.inkSoft, marginBottom: 6, fontWeight: 500 }}>Sync direction</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[['two-way', 'Two-way', 'Changes flow both directions'], ['push', 'One-way push', 'Hub → calendar only']].map(([val, lab, d]) => (
              <button key={val} onClick={() => setDirection(val)} style={{
                flex: 1, textAlign: 'left', cursor: 'pointer', padding: '11px 13px',
                borderRadius: 10, background: direction === val ? t.okBg : t.card,
                border: `1.5px solid ${direction === val ? t.ok : t.border}`,
              }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: t.ink }}>{lab}</div>
                <div style={{ fontSize: 11.5, color: t.inkSoft, marginTop: 2 }}>{d}</div>
              </button>
            ))}
          </div>
        </div>
        <SelectInput t={t} label="Reminder lead time" value={lead} onChange={setLead}
          options={['At time of routine', '1 hour before', '1 day before', '2 days before', '1 week before']}/>
      </div>
      <PfModalFooter t={t}>
        <Btn t={t} onClick={() => nav.closeOverlays()}>Cancel</Btn>
        <Btn t={t} primary onClick={save}><HIcon kind="link" size={14}/> {ctx.conn ? 'Save changes' : `Connect ${provider.name}`}</Btn>
      </PfModalFooter>
    </PfModalShell>
  );
};

// ---------- shared modal chrome ----------
const PfModalShell = ({ t, title, sub, icon, onClose, width = 460, children }) => (
  <div onClick={onClose} style={{
    position: 'fixed', inset: 0, background: 'rgba(20,18,12,0.34)', backdropFilter: 'blur(2px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 24,
  }}>
    <div onClick={e => e.stopPropagation()} style={{
      width: '100%', maxWidth: width, background: t.card, borderRadius: 16,
      border: `1px solid ${t.border}`, boxShadow: '0 24px 60px rgba(20,18,12,0.22)',
      maxHeight: '90vh', overflowY: 'auto',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '20px 22px 16px', borderBottom: `1px solid ${t.divider}` }}>
        {icon}
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: PF_DISPLAY, fontSize: 20, fontWeight: 600, color: t.ink, letterSpacing: -0.3 }}>{title}</div>
          {sub && <div style={{ fontSize: 13, color: t.inkSoft, marginTop: 3 }}>{sub}</div>}
        </div>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: t.inkFaint, fontSize: 22, lineHeight: 1, padding: 0 }}>×</button>
      </div>
      <div style={{ padding: '18px 22px 6px' }}>{children}</div>
    </div>
  </div>
);

const PfModalFooter = ({ t, children }) => (
  <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '16px 0 18px', marginTop: 4 }}>{children}</div>
);

Object.assign(window, {
  HifiProfileScreen, HifiPasswordModal, HifiCalendarModal,
  PfToggle, SectionCard, PfModalShell, PfModalFooter,
});
