// Profile / bio page
const { useState: useStateP, useEffect: useEffectP } = React;

const COMPANION_OPTS = [
  { id: 'solo', label: 'Solo' },
  { id: 'partner', label: 'With partner' },
  { id: 'family', label: 'Family with kids' },
  { id: 'friends', label: 'Friends' },
  { id: 'group', label: 'Larger group' },
];
const PACE_OPTS = [
  { id: 'slow', label: 'Slow nomad (3+ months)' },
  { id: 'medium', label: 'Medium (1–3 months)' },
  { id: 'fast', label: 'Fast hopper (<1 month)' },
];
const WORK_OPTS = [
  { id: 'remote-employed', label: 'Remote employee' },
  { id: 'freelance', label: 'Freelance / contractor' },
  { id: 'business', label: 'Business owner' },
  { id: 'between', label: 'Between gigs' },
  { id: 'other', label: 'Other' },
];
const BUDGET_OPTS = [
  { id: 'survival', label: 'Survival mode' },
  { id: 'comfort', label: 'Comfortable' },
  { id: 'luxury', label: 'Luxury' },
];

function ProfilePage() {
  const store = useStore();
  const user = store.getCurrentUser();
  const [draft, setDraft] = useStateP(user?.profile || {});
  const [savedAt, setSavedAt] = useStateP(null);

  useEffectP(() => { if (user) setDraft(user.profile); }, [user?.id]);

  if (!user) return <div className="page-empty">Sign in to set up your profile.</div>;

  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));
  const save = () => {
    store.updateProfile(draft);
    setSavedAt(Date.now());
    setTimeout(() => setSavedAt(null), 2200);
  };

  const addItem = (key, val) => {
    val = val.trim(); if (!val) return;
    set(key, [...(draft[key] || []), val]);
  };
  const removeItem = (key, i) => set(key, (draft[key] || []).filter((_, j) => j !== i));

  return (
    <div className="page profile-page">
      <div className="page-head">
        <div>
          <div className="loc-kicker">YOU · {user.email.toUpperCase()}</div>
          <h1 className="page-title">Your bio</h1>
          <div className="page-sub">The more Claude knows about your situation, the better it can tailor recommendations and proactive suggestions.</div>
        </div>
      </div>

      <div className="profile-grid">
        <Section title="Identity">
          <Field label="Display name">
            <input className="settings-input" value={draft.handle || user.name || ''} onChange={e => set('handle', e.target.value)}/>
          </Field>
          <Field label="Current location">
            <input className="settings-input" placeholder="e.g. Brooklyn, NY"
              value={draft.currentLocation || ''} onChange={e => set('currentLocation', e.target.value)}/>
          </Field>
          <Field label="Citizenship(s)" hint="Affects visa logic for recommendations.">
            <ChipInput value={draft.citizenships || []} onAdd={v => addItem('citizenships', v)} onRemove={i => removeItem('citizenships', i)} placeholder="e.g. US, then Enter"/>
          </Field>
          <Field label="Languages spoken">
            <ChipInput value={draft.languages || []} onAdd={v => addItem('languages', v)} onRemove={i => removeItem('languages', i)} placeholder="e.g. English, Portuguese"/>
          </Field>
        </Section>

        <Section title="Work">
          <Field label="Profession">
            <input className="settings-input" placeholder="e.g. Product designer"
              value={draft.profession || ''} onChange={e => set('profession', e.target.value)}/>
          </Field>
          <Field label="Industry">
            <input className="settings-input" placeholder="e.g. Fintech"
              value={draft.industry || ''} onChange={e => set('industry', e.target.value)}/>
          </Field>
          <Field label="Setup">
            <RadioRow opts={WORK_OPTS} value={draft.workSetup} onChange={v => set('workSetup', v)}/>
          </Field>
          <Field label="Budget tier">
            <RadioRow opts={BUDGET_OPTS} value={draft.budgetTier} onChange={v => set('budgetTier', v)}/>
          </Field>
        </Section>

        <Section title="Travel context">
          <Field label="Who's coming?">
            <RadioRow opts={COMPANION_OPTS} value={draft.companions} onChange={v => set('companions', v)}/>
          </Field>
          {draft.companions === 'family' && (
            <Field label="Kids' ages">
              <ChipInput value={draft.kidAges || []} onAdd={v => addItem('kidAges', v)} onRemove={i => removeItem('kidAges', i)} placeholder="e.g. 4, 7"/>
            </Field>
          )}
          <Field label="Pets">
            <ChipInput value={draft.pets || []} onAdd={v => addItem('pets', v)} onRemove={i => removeItem('pets', i)} placeholder="e.g. cat, dog"/>
          </Field>
          <Field label="Pace">
            <RadioRow opts={PACE_OPTS} value={draft.pace} onChange={v => set('pace', v)}/>
          </Field>
        </Section>

        <Section title="Preferences">
          <Field label="Health considerations" hint="e.g. dietary, medical, accessibility — kept private.">
            <textarea className="settings-input bio-text" rows="2"
              value={draft.health || ''} onChange={e => set('health', e.target.value)}/>
          </Field>
          <Field label="Lifestyle">
            <textarea className="settings-input bio-text" rows="3" placeholder="What does an ideal day look like? Surf, gym, climbing, museums, dive bars…"
              value={draft.lifestyle || ''} onChange={e => set('lifestyle', e.target.value)}/>
          </Field>
          <Field label="Anything else?">
            <textarea className="settings-input bio-text" rows="3"
              value={draft.bio || ''} onChange={e => set('bio', e.target.value)}/>
          </Field>
        </Section>
      </div>

      <button className={`profile-save-fab ${savedAt ? 'saved' : ''}`} onClick={save} disabled={!!savedAt} title="Save profile">
        {savedAt ? (
          <span className="profile-save-confirm">
            <span className="check-circle">
              <svg viewBox="0 0 52 52" width="22" height="22">
                <circle className="check-c" cx="26" cy="26" r="24" fill="none" stroke="currentColor" strokeWidth="2.5"/>
                <path className="check-m" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round" d="M14 27 l8 8 l16 -18"/>
              </svg>
            </span>
            <span>Saved</span>
          </span>
        ) : (
          <span>Save profile →</span>
        )}
      </button>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div className="profile-section">
      <div className="profile-section-title">{title}</div>
      {children}
    </div>
  );
}
function Field({ label, hint, children }) {
  return (
    <div className="profile-field">
      <div className="filter-label">{label}</div>
      {children}
      {hint && <div className="profile-hint">{hint}</div>}
    </div>
  );
}
function RadioRow({ opts, value, onChange }) {
  return (
    <div className="radio-row">
      {opts.map(o => (
        <button key={o.id} className={`chip ${value === o.id ? 'on' : ''}`} onClick={() => onChange(o.id)}>{o.label}</button>
      ))}
    </div>
  );
}
function ChipInput({ value, onAdd, onRemove, placeholder }) {
  const [t, setT] = useStateP('');
  const commit = () => { if (t.trim()) { onAdd(t); setT(''); } };
  return (
    <div className="chip-input">
      <div className="chip-input-chips">
        {(value || []).map((v, i) => (
          <span key={i} className="chip on">{v}<button onClick={() => onRemove(i)}>×</button></span>
        ))}
      </div>
      <input className="settings-input" placeholder={placeholder}
        value={t} onChange={e => setT(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter') { commit(); } }}
        onBlur={commit}/>
    </div>
  );
}

window.ProfilePage = ProfilePage;
