// screens-edit-profile.jsx — Add / Edit psychologist profile
// Used by:
//   - Psychologist persona: edit own profile (from Dashboard CTA)
//   - Admin persona: add a new psychologist (from queue header CTA)

const BLANK_PSY = {
  name: '',
  credentials: '',
  initials: '',
  avatarVariant: 'a',
  avatarData: null,
  bio: '',
  longBio: '',
  approaches: [],
  primaryApproach: null,
  specializations: [],
  district: 'Nicosia',
  address: '',
  coords: null,
  modes: ['in-person'],
  gesy: false,
  pricePerSession: 60,
  sessionLengthMin: 50,
  languages: ['Greek', 'English'],
  yearsExperience: 1,
  education: [],
  experience: [],
  introCall: true,
  chatEnabled: true,
  verified: false,
};

function EditProfileScreen({ psyId, isAdmin, onSave, onCancel, setToast, onSignOut, onAvatarChange }) {
  const { t } = useLang();
  const [form, setForm] = useState({ ...BLANK_PSY });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [deleteConfirming, setDeleteConfirming] = useState(false);
  const [deletingAccount, setDeletingAccount] = useState(false);
  const isNew = !psyId;

  // Load existing profile from API
  useEffect(() => {
    if (!psyId) { setLoading(false); return; }
    const endpoint = isAdmin ? API.getPsychologist(psyId) : API.getMyProfile();
    endpoint
      .then(data => {
        if (data) {
          const coords = data.lat && data.lon ? { lat: data.lat, lon: data.lon } : null;
          setForm({ ...BLANK_PSY, ...data, coords });
        }
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [psyId]);

  function up(k, v) { setForm(f => ({ ...f, [k]: v })); }
  function toggleIn(k, v) {
    const cur = new Set(form[k] || []);
    if (cur.has(v)) cur.delete(v); else cur.add(v);
    setForm(f => ({ ...f, [k]: Array.from(cur) }));
  }
  function addRow(k) { setForm(f => ({ ...f, [k]: [...(f[k] || []), { year: '', text: '' }] })); }
  function updateRow(k, i, field, v) {
    const next = [...form[k]];
    next[i] = { ...next[i], [field]: v };
    setForm(f => ({ ...f, [k]: next }));
  }
  function removeRow(k, i) { setForm(f => ({ ...f, [k]: f[k].filter((_, j) => j !== i) })); }

  useEffect(() => {
    if (form.primaryApproach && !form.approaches.includes(form.primaryApproach)) {
      setForm(f => ({ ...f, primaryApproach: f.approaches[0] || null }));
    }
    if (!form.primaryApproach && form.approaches.length > 0) {
      setForm(f => ({ ...f, primaryApproach: f.approaches[0] }));
    }
  }, [form.approaches]);

  async function handleDeleteAccount() {
    setDeletingAccount(true);
    try {
      const res = await fetch('/api/users/me', { method: 'DELETE', headers: authHeaders() });
      if (res.ok && onSignOut) onSignOut();
    } catch { setDeletingAccount(false); }
  }

  async function save() {
    setSaving(true);
    try {
      if (isAdmin && psyId) {
        // Admin editing an existing profile — use the admin endpoint
        await API.saveAdminProfile(psyId, form);
      } else {
        // Psychologist editing their own profile (or admin creating a new one)
        await API.saveMyProfile(form);
      }
      setToast(isNew ? 'Profile created — it will appear in the directory.' : 'Profile saved.');
      // Small delay so the toast is visible before the screen transitions
      setTimeout(function() { onSave(form); }, 1200);
    } catch (e) {
      setToast(e.message || 'Failed to save.');
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <div className="page narrow" style={{ paddingTop: 60, textAlign: 'center' }}>
        <Icon name="sync" style={{ fontSize: 36, color: 'var(--fg3)' }} />
        <p style={{ color: 'var(--fg2)', marginTop: 12 }}>Loading profile…</p>
      </div>
    );
  }

  return (
    <div className="page" style={{ maxWidth: 960 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, marginBottom: 32 }}>
        <div>
          <div style={{ marginBottom: 32 }}>
            <button className="btn link" onClick={onCancel} style={{ fontSize: 13 }}>
              <Icon name="arrow_back" className="sm" /> {isNew ? t('edit_back_queue') : isAdmin ? t('edit_back_profile') : t('edit_back_dashboard')}
            </button>
          </div>
          <span className="eyebrow muted">{isAdmin ? t('edit_eyebrow_admin') : t('edit_eyebrow_own')}</span>
          <h1 className="display" style={{ fontSize: 38, marginTop: 6, textWrap: 'balance' }}>
            {isNew ? t('edit_h1_new') : isAdmin ? t('edit_h1_admin') : t('edit_h1_own')}
          </h1>
          <p style={{ color: 'var(--fg2)', marginTop: 8, fontSize: 15, lineHeight: 1.5, maxWidth: 560 }}>
            {isNew ? t('edit_sub_new') : t('edit_sub_own')}
          </p>
        </div>
        <div style={{ display: 'flex', gap: 10, position: 'sticky', top: 88 }}>
          <button className="btn ghost" onClick={onCancel}>{t('btn_cancel')}</button>
          <button className="btn primary" onClick={save} disabled={!form.name || (isNew && form.approaches.length === 0) || saving}>
            <Icon name="check" className="sm" /> {isNew ? t('edit_add_psy') : t('btn_save')}
          </button>
        </div>
      </div>

      <div style={{ display: 'grid', gap: 24 }}>
        {/* ====== Identity ====== */}
        <Section title={t('edit_sec_identity')}>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 24, alignItems: 'flex-start' }}>
            <div>
              <div className={`avatar-large ${form.avatarVariant}`} style={{ overflow: 'hidden', padding: 0, display: 'grid', placeItems: 'center' }}>
                {form.avatarData
                  ? <img src={form.avatarData} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  : (form.initials || form.name.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase()) || '?'}
              </div>
              <label className="btn ghost sm" style={{ marginTop: 12, width: '100%', cursor: 'pointer', justifyContent: 'center' }}>
                <Icon name="photo_camera" className="sm" /> Upload photo
                <input type="file" accept="image/*" style={{ display: 'none' }} onChange={e => {
                  const file = e.target.files[0];
                  if (!file) return;
                  const reader = new FileReader();
                  reader.onload = ev => { up('avatarData', ev.target.result); onAvatarChange && onAvatarChange(ev.target.result); };
                  reader.readAsDataURL(file);
                }} />
              </label>
              {form.avatarData && (
                <button className="btn ghost sm" style={{ marginTop: 6, width: '100%', fontSize: 12, color: 'var(--fg3)' }} onClick={() => { up('avatarData', null); onAvatarChange && onAvatarChange(null); }}>
                  Remove photo
                </button>
              )}
              <div style={{ display: 'flex', gap: 4, marginTop: 8, justifyContent: 'center' }}>
                {['a','b','c','d','e'].map(v => (
                  <button key={v}
                    onClick={() => up('avatarVariant', v)}
                    title="Choose fallback color"
                    style={{
                      width: 18, height: 18, borderRadius: '50%',
                      border: form.avatarVariant === v ? '2px solid var(--psy-ink)' : '1px solid var(--psy-rule)',
                      cursor: 'pointer',
                      background:
                        v === 'a' ? 'var(--psy-accent)' :
                        v === 'b' ? '#4d7c5a' :
                        v === 'c' ? '#2581eb' :
                        v === 'd' ? '#b04d70' :
                                    '#b08a3d',
                    }} />
                ))}
              </div>
            </div>

            <div style={{ display: 'grid', gap: 14 }}>
              <Field label="Full name" required>
                <input className="input" value={form.name} onChange={e => up('name', e.target.value)} placeholder="Dr. Elena Constantinou" />
              </Field>
              <Field label="Credentials (shown under your name)" sub="Enter in any language — automatically translated for visitors">
                <input className="input" value={form.credentials} onChange={e => up('credentials', e.target.value)} placeholder="MSc Clinical Psychology · Licensed Psychologist" />
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <Field label="Years of experience">
                  <input className="input" type="number" min="0" value={form.yearsExperience} onChange={e => up('yearsExperience', +e.target.value)} />
                </Field>
                <Field label="Initials (for placeholders)">
                  <input className="input" maxLength={3} value={form.initials} onChange={e => up('initials', e.target.value.toUpperCase())} placeholder="EC" />
                </Field>
              </div>
            </div>
          </div>
        </Section>

        {/* ====== Bio ====== */}
        <Section title={t('edit_sec_about')}>
          <Field label="Short bio" sub="One paragraph — shows on directory cards.">
            <textarea className="textarea" value={form.bio} maxLength={280}
              onChange={e => up('bio', e.target.value)}
              placeholder="I work mostly with adults navigating anxiety, perfectionism, and burnout. My approach is collaborative…" />
            <div style={{ fontSize: 11, color: 'var(--fg3)', textAlign: 'right', marginTop: 4 }}>{form.bio.length}/280</div>
          </Field>
          <Field label="Full bio" sub="Shown on your profile under ‘About’.">
            <textarea className="textarea" style={{ minHeight: 180 }} value={form.longBio}
              onChange={e => up('longBio', e.target.value)}
              placeholder="I’ve been practising in Nicosia for 12 years. I trained at…" />
          </Field>
        </Section>

        {/* ====== Approach & specialisations ====== */}
        <Section title={t('edit_sec_approach')}>
          <Field label="Therapeutic approaches" sub="Pick everything you’re trained in. Set a primary below.">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {APPROACHES.map(a => {
                const on = form.approaches.includes(a.id);
                return (
                  <button key={a.id}
                    onClick={() => toggleIn('approaches', a.id)}
                    title={a.short}
                    className="tag"
                    style={{
                      padding: '8px 14px',
                      cursor: 'pointer',
                      background: on ? 'var(--psy-ink)' : 'white',
                      color: on ? 'white' : 'var(--psy-ink)',
                      borderColor: on ? 'var(--psy-ink)' : 'var(--psy-rule)',
                      fontSize: 13,
                      fontWeight: on ? 600 : 500,
                    }}>
                    {on && <Icon name="check" className="sm" />} {a.long}
                  </button>
                );
              })}
            </div>
          </Field>

          {form.approaches.length > 0 && (
            <Field label="Primary approach" sub="The one you’re known for. We tag the profile with this.">
              <select className="select" value={form.primaryApproach || ''} onChange={e => up('primaryApproach', e.target.value)}>
                {form.approaches.map(id => {
                  const a = APPROACHES.find(x => x.id === id);
                  return <option key={id} value={id}>{a?.long}</option>;
                })}
              </select>
            </Field>
          )}

          <Field label="Specialisations" sub="Issues you actively work with. Surface in search filters.">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {SPECIALIZATIONS.map(s => {
                const on = form.specializations.includes(s.id);
                return (
                  <button key={s.id}
                    onClick={() => toggleIn('specializations', s.id)}
                    className="tag"
                    style={{
                      padding: '8px 14px',
                      cursor: 'pointer',
                      background: on ? 'var(--psy-accent-soft)' : 'white',
                      color: on ? 'color-mix(in oklab, var(--psy-accent) 70%, black)' : 'var(--psy-ink)',
                      borderColor: on ? 'transparent' : 'var(--psy-rule)',
                      fontSize: 13,
                      fontWeight: on ? 600 : 500,
                    }}>
                    {on && <Icon name="check" className="sm" />} {s.name}
                  </button>
                );
              })}
            </div>
          </Field>
        </Section>

        {/* ====== Format & fees ====== */}
        <Section title={t('edit_sec_format')}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Field label="Session format">
              <div style={{ display: 'flex', gap: 8 }}>
                {['in-person', 'online'].map(m => {
                  const on = form.modes.includes(m);
                  return (
                    <button key={m} className="btn ghost sm"
                      onClick={() => toggleIn('modes', m)}
                      style={on ? { background: 'var(--psy-ink)', color: 'white', borderColor: 'var(--psy-ink)' } : null}>
                      <Icon name={m === 'online' ? 'videocam' : 'meeting_room'} className="sm" />
                      {m === 'online' ? t('lbl_online') : t('lbl_inperson')}
                    </button>
                  );
                })}
              </div>
            </Field>
            <Field label="GeSY (national health system)">
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 14px', background: 'white', border: '1px solid var(--psy-rule)', borderRadius: 12, fontSize: 14, cursor: 'pointer' }}>
                <input type="checkbox" checked={form.gesy} onChange={() => up('gesy', !form.gesy)} style={{ accentColor: 'var(--psy-ink)' }} />
                I accept GeSY referrals
              </label>
            </Field>
            <Field label="Price per session (€)">
              <input className="input" type="number" min="0" value={form.pricePerSession} onChange={e => up('pricePerSession', +e.target.value)} />
            </Field>
            <Field label="Session length (min)">
              <input className="input" type="number" min="30" step="5" value={form.sessionLengthMin || 50} onChange={e => up('sessionLengthMin', +e.target.value)} />
            </Field>
          </div>
        </Section>

        {/* ====== Location ====== */}
        <Section title={t('edit_sec_location')}>
          <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 16 }}>
            <Field label="District">
              <select className="select" value={form.district} onChange={e => up('district', e.target.value)}>
                {DISTRICTS.map(d => <option key={d} value={d}>{d}</option>)}
              </select>
            </Field>
            <Field label="Office address (street, building, city)">
              <AddressInput
                value={form.address}
                onChange={v => up('address', v)}
                onCoords={coords => up('coords', coords)}
                district={form.district}
              />
            </Field>
          </div>
          <MapPreview address={form.address} coords={form.coords} district={form.district} />

        </Section>

        {/* ====== Languages ====== */}
        <Section title={t('edit_sec_languages')}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {LANGUAGES.map(l => {
              const on = form.languages.includes(l);
              return (
                <button key={l}
                  onClick={() => toggleIn('languages', l)}
                  className="tag"
                  style={{
                    padding: '8px 14px',
                    cursor: 'pointer',
                    background: on ? 'var(--psy-ink)' : 'white',
                    color: on ? 'white' : 'var(--psy-ink)',
                    borderColor: on ? 'var(--psy-ink)' : 'var(--psy-rule)',
                    fontSize: 13,
                  }}>
                  {on && <Icon name="check" className="sm" />} {l}
                </button>
              );
            })}
          </div>
        </Section>

        {/* ====== Education ====== */}
        <Section title={t('edit_sec_education')}
          action={<button className="btn ghost sm" onClick={() => addRow('education')}><Icon name="add" className="sm" /> Add entry</button>}>
          {form.education.length === 0
            ? <Empty text="No education entries yet." />
            : form.education.map((e, i) => (
              <RowEdit key={i} item={e} onYear={v => updateRow('education', i, 'year', v)} onText={v => updateRow('education', i, 'text', v)} onRemove={() => removeRow('education', i)} placeholder="MSc, Psychology — King's College London" />
            ))}
        </Section>

        {/* ====== Experience ====== */}
        <Section title={t('edit_sec_experience')}
          action={<button className="btn ghost sm" onClick={() => addRow('experience')}><Icon name="add" className="sm" /> Add entry</button>}>
          {form.experience.length === 0
            ? <Empty text="No experience entries yet." />
            : form.experience.map((e, i) => (
              <RowEdit key={i} item={e} onYear={v => updateRow('experience', i, 'year', v)} onText={v => updateRow('experience', i, 'text', v)} onRemove={() => removeRow('experience', i)} placeholder="Senior Psychologist, Makarios III Hospital" />
            ))}
        </Section>

        {/* ====== Communication & visibility ====== */}
        <Section title={t('edit_sec_comms')}>
          <ToggleRow label="Free 15-minute intro call" sub="Many clients book this first. We recommend keeping it on." value={form.introCall} onChange={v => up('introCall', v)} />
          <ToggleRow label="Allow direct chat" sub="Clients can message you without booking first. You decide when to reply." value={form.chatEnabled} onChange={v => up('chatEnabled', v)} />
          {isAdmin && (
            <ToggleRow label="Mark as verified" sub="Admin-only. Bypasses the queue. Use with care." value={form.verified} onChange={v => up('verified', v)} />
          )}
        </Section>

        {/* Footer save */}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 16 }}>
          <button className="btn ghost" onClick={onCancel}>{t('btn_cancel')}</button>
          <button className="btn primary lg" onClick={save} disabled={!form.name || (!isAdmin && form.approaches.length === 0) || saving}>
            <Icon name="check" className="sm" /> {isNew ? t('edit_add_psy') : t('btn_save')}
          </button>
        </div>

      </div>
    </div>
  );
}

// ---------- helpers ----------
function Section({ title, action, children }) {
  return (
    <section className="card" style={{ padding: 28 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
        <h3 className="display" style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.015em' }}>{title}</h3>
        {action}
      </div>
      <div style={{ display: 'grid', gap: 14 }}>{children}</div>
    </section>
  );
}
function Field({ label, sub, required, children }) {
  return (
    <div>
      <div className="field-label" style={{ marginBottom: 6 }}>
        {label}{required && <span style={{ color: 'var(--color-error)', marginLeft: 4 }}>*</span>}
        {sub && <span style={{ display: 'block', fontWeight: 400, color: 'var(--fg3)', fontSize: 12, marginTop: 2 }}>{sub}</span>}
      </div>
      {children}
    </div>
  );
}
function RowEdit({ item, onYear, onText, onRemove, placeholder }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr 40px', gap: 10, alignItems: 'center' }}>
      <input className="input" value={item.year} onChange={e => onYear(e.target.value)} placeholder="2018" />
      <input className="input" value={item.text} onChange={e => onText(e.target.value)} placeholder={placeholder} />
      <button className="nav-icon-btn" onClick={onRemove} title="Remove" style={{ width: 36, height: 36 }}>
        <Icon name="delete" className="sm" style={{ color: 'var(--color-error)' }} />
      </button>
    </div>
  );
}
function ToggleRow({ label, sub, value, onChange }) {
  return (
    <label style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '12px 14px', background: 'var(--psy-surface)', borderRadius: 12, cursor: 'pointer' }}>
      <input type="checkbox" checked={value} onChange={() => onChange(!value)} style={{ width: 18, height: 18, accentColor: 'var(--psy-ink)' }} />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: 'var(--fg2)', marginTop: 2 }}>{sub}</div>}
      </div>
    </label>
  );
}
function Empty({ text }) {
  return (
    <div style={{ padding: 18, textAlign: 'center', color: 'var(--fg3)', background: 'var(--psy-surface)', borderRadius: 12, fontSize: 13 }}>
      {text}
    </div>
  );
}

Object.assign(window, { EditProfileScreen, BLANK_PSY });
