// itrymo — Profile / menu (mobile). Home for account, preferences,
// support + legal links. Loaded after proto-shared.jsx + proto-favorites.jsx.

const LANGS = [
  { id: 'en', label: 'English', short: 'EN' },
  { id: 'ja', label: '日本語', short: 'JA' },
  { id: 'zh', label: '中文', short: 'ZH' },
  { id: 'ko', label: '한국어', short: 'KO' },
];
const CURRENCIES = [
  { id: 'jpy', label: 'Japanese Yen', sym: '¥', short: 'JPY' },
  { id: 'usd', label: 'US Dollar', sym: '$', short: 'USD' },
  { id: 'eur', label: 'Euro', sym: '€', short: 'EUR' },
  { id: 'gbp', label: 'British Pound', sym: '£', short: 'GBP' },
];

function usePref(key, fallback) {
  const [v, setV] = React.useState(() => {
    try { return localStorage.getItem(key) || fallback; } catch { return fallback; }
  });
  const set = (val) => { setV(val); try { localStorage.setItem(key, val); window.dispatchEvent(new Event('itrymo_pref_change')); } catch (e) {} };
  return [v, set];
}

// A single tappable row with a value on the right (expands options inline).
function PrefRow({ icon, label, value, open, onToggle, children, last }) {
  return (
    <div style={{ borderBottom: last ? 'none' : `1px solid ${T.borderSoft}` }}>
      <button onClick={onToggle} style={{
        all: 'unset', cursor: 'pointer', width: '100%', boxSizing: 'border-box',
        padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        {icon && (
          <div style={{
            width: 30, height: 30, borderRadius: 9, background: T.bg, flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.faintInk,
          }}><Icon name={icon} size={15} /></div>
        )}
        <span style={{ fontSize: 14, fontWeight: 600, flex: 1 }}>{label}</span>
        <span style={{ fontSize: 13, color: T.muted, fontWeight: 500, whiteSpace: 'nowrap' }}>{value}</span>
        <Icon name="chevR" size={14} color={T.muted}
              style={{ transform: open ? 'rotate(90deg)' : 'none', transition: 'transform .15s' }} />
      </button>
      {open && <div style={{ padding: '0 16px 14px' }}>{children}</div>}
    </div>
  );
}

function OptionList({ options, value, onPick, render }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      {options.map((o) => {
        const on = o.id === value;
        return (
          <button key={o.id} onClick={() => onPick(o.id)} style={{
            all: 'unset', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 12px', borderRadius: 10,
            background: on ? T.selBg : '#fff', color: on ? T.selFg : T.ink,
            border: `1px solid ${on ? T.selBg : T.border}`,
          }}>
            <span style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>{render(o)}</span>
            {on && <Icon name="check" size={14} color={T.selFg} />}
          </button>
        );
      })}
    </div>
  );
}

function SectionCard({ title, children }) {
  return (
    <div style={{ marginTop: 18 }}>
      {title && (
        <div style={{
          fontSize: 11, color: T.muted, fontWeight: 700, letterSpacing: 0.5,
          textTransform: 'uppercase', padding: '0 4px 8px',
        }}>{title}</div>
      )}
      <div style={{ background: '#fff', borderRadius: 14, border: `1px solid ${T.borderSoft}`, overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}

function LinkRow({ label, onClick, last }) {
  return (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer', width: '100%', boxSizing: 'border-box',
      padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: last ? 'none' : `1px solid ${T.borderSoft}`,
    }}>
      <span style={{ fontSize: 14, fontWeight: 500, flex: 1 }}>{label}</span>
      <Icon name="chevR" size={14} color={T.muted} />
    </button>
  );
}

function ProfileView({ surface = 'mobile', city = 'Tokyo', accounts = false, onClose, onOpenFavorites, onOpenPage }) {
  useEscClose(onClose);
  const favIds = useFavorites();
  const [lang, setLang] = usePref('itrymo_lang', 'en');
  const [cur, setCur] = usePref('itrymo_currency', 'jpy');
  const [open, setOpen] = React.useState(null); // 'lang' | 'currency' | 'city'

  const langObj = LANGS.find((l) => l.id === lang) || LANGS[0];
  const curObj = CURRENCIES.find((c) => c.id === cur) || CURRENCIES[0];
  const toggle = (k) => setOpen((o) => (o === k ? null : k));

  const header = (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: surface === 'mobile' ? '14px 18px' : '16px 20px',
      background: '#fff', borderBottom: `1px solid ${T.borderSoft}`, flexShrink: 0,
    }}>
      {surface === 'mobile' && (
        <button onClick={onClose} title="Back" style={{
          all: 'unset', cursor: 'pointer', width: 34, height: 34, borderRadius: 17,
          background: T.bg, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="chevR" size={16} style={{ transform: 'rotate(180deg)' }} />
        </button>
      )}
      <h2 style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.4, flex: 1, margin: 0 }}>{accounts ? 'Account' : 'Settings'}</h2>
      {surface === 'web' && (
        <button onClick={onClose} title="Close" style={{
          all: 'unset', cursor: 'pointer', width: 30, height: 30, borderRadius: 15,
          background: '#F4EFE6', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="close" size={13} /></button>
      )}
    </div>
  );

  const content = (
    <React.Fragment>
        {accounts ? (
        /* Account identity */
        <div style={{
          background: '#fff', borderRadius: 14, border: `1px solid ${T.borderSoft}`,
          padding: 16, display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 52, height: 52, borderRadius: 26, background: T.accentBg, color: T.accent,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 700,
          }}>JL</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700 }}>Jamie Lee</div>
            <div style={{ fontSize: 13, color: T.muted }}>jamie.lee@email.com</div>
          </div>
          <button style={{
            all: 'unset', cursor: 'pointer', fontSize: 13, color: T.accent, fontWeight: 600,
          }}>Edit</button>
        </div>
        ) : (
        /* No account yet — explain device-only saves */
        <div style={{
          background: T.accentBg, borderRadius: 14, border: `1px solid ${T.accentBd}`,
          padding: 16, display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 19, background: '#fff', flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.accent,
          }}><Icon name="heart" size={17} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: T.ink }}>Your saved places live on this device</div>
            <div style={{ fontSize: 12, color: T.faintInk, marginTop: 2 }}>Accounts &amp; sync are coming soon.</div>
          </div>
        </div>
        )}

        {/* Preferences */}
        <SectionCard title="Preferences">
          <PrefRow icon="globe" label="Language" value={langObj.short}
                   open={open === 'lang'} onToggle={() => toggle('lang')}>
            <OptionList options={LANGS} value={lang} onPick={(id) => { setLang(id); setOpen(null); }}
                        render={(o) => `${o.label} · ${o.short}`} />
            {lang !== 'en' && (
              <div style={{ fontSize: 12, color: '#B36A00', padding: '8px 10px', background: '#FFF8EE', borderRadius: 8, marginTop: 6 }}>
                🌏 {LANGS.find(l => l.id === lang)?.label} translation coming soon — showing English for now.
              </div>
            )}
          </PrefRow>
          <PrefRow icon="bookmark" label="Currency" value={`${curObj.sym} ${curObj.short}`}
                   open={open === 'currency'} onToggle={() => toggle('currency')}>
            <OptionList options={CURRENCIES} value={cur} onPick={(id) => { setCur(id); setOpen(null); }}
                        render={(o) => `${o.sym}  ${o.label}`} />
          </PrefRow>
          <PrefRow icon="pin" label="City" value={city} last
                   open={open === 'city'} onToggle={() => toggle('city')}>
            <div style={{ fontSize: 12.5, color: T.muted, padding: '4px 2px', lineHeight: 1.5 }}>
              itrymo is in <strong style={{ color: T.ink }}>{city}</strong> today. More cities are coming soon.
            </div>
          </PrefRow>
        </SectionCard>

        {/* Activity */}
        <SectionCard title="Activity">
          <button onClick={onOpenFavorites} style={{
            all: 'unset', cursor: 'pointer', width: '100%', boxSizing: 'border-box',
            padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: 9, background: T.bg, flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><Icon name="heart" size={15} color="#E0533D" fill={favIds.length ? '#E0533D' : 'none'} /></div>
            <span style={{ fontSize: 14, fontWeight: 600, flex: 1 }}>Saved places</span>
            <span style={{ fontSize: 13, color: T.muted, fontWeight: 500 }}>{favIds.length}</span>
            <Icon name="chevR" size={14} color={T.muted} />
          </button>
        </SectionCard>

        {/* Support & legal — formerly the footer links */}
        <SectionCard title="About & support">
          <LinkRow label="About itrymo" onClick={() => onOpenPage && onOpenPage('about')} />
          <LinkRow label="Help & support" onClick={() => onOpenPage && onOpenPage('help')} />
          <LinkRow label="Privacy policy" onClick={() => onOpenPage && onOpenPage('privacy')} />
          <LinkRow label="Terms of service" onClick={() => onOpenPage && onOpenPage('terms')} last />
        </SectionCard>

        {/* Sign out (only when signed in) */}
        {accounts && (
        <button onClick={() => {
          try { localStorage.removeItem('itrymo_accounts'); } catch {}
          window.location.reload();
        }} style={{
          all: 'unset', cursor: 'pointer', marginTop: 18, width: '100%', boxSizing: 'border-box',
          height: 48, borderRadius: 12, border: `1px solid ${T.border}`, background: '#fff',
          color: '#C0492F', fontWeight: 600, fontSize: 14, textAlign: 'center',
        }}>Sign out</button>
        )}

        <div style={{ textAlign: 'center', marginTop: 22 }}>
          <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: -0.3, color: T.ink }}>
            itrymo<span style={{ color: T.accent }}>.</span>
          </div>
          <div style={{ fontSize: 11, color: T.muted, marginTop: 3 }}>Version 1.0 · © 2026 itrymo</div>
        </div>
    </React.Fragment>
  );

  if (surface === 'mobile') {
    return (
      <div role="dialog" aria-modal="true" aria-label={accounts ? 'Account' : 'Settings'} style={{
        position: 'absolute', inset: 0, background: T.bg, zIndex: 75,
        display: 'flex', flexDirection: 'column', animation: 'itrymo-slideup .22s ease',
      }}>
        {header}
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 28px' }}>{content}</div>
      </div>
    );
  }

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 75, background: 'rgba(20,18,14,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
      animation: 'itrymo-fade .18s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label={accounts ? 'Account' : 'Settings'} style={{
        width: '100%', maxWidth: 480, maxHeight: '88vh', background: T.bg,
        borderRadius: 18, overflow: 'hidden', display: 'flex', flexDirection: 'column',
        boxShadow: '0 30px 80px rgba(0,0,0,0.30)', animation: 'itrymo-pop .2s ease',
      }}>
        {header}
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 28px' }}>{content}</div>
      </div>
    </div>
  );
}

Object.assign(window, { ProfileView, LANGS, CURRENCIES, usePref });
