// Profile & Settings

function ProfileSettings() {
  const { user } = useAuth();
  const [form, setForm] = React.useState(() => profileFormFromUser(user));
  const [activeTab, setActiveTab] = React.useState('personal');
  const [busy, setBusy] = React.useState(false);
  const [status, setStatus] = React.useState('');
  const [err, setErr] = React.useState('');
  const [prefs, setPrefs] = React.useState({
    reminders: true,
    prescriptions: true,
    dentistMessages: true,
    healthTips: false,
  });
  const [language, setLanguage] = React.useState('English (India)');
  const [family, setFamily] = React.useState([]);
  const [familyDraft, setFamilyDraft] = React.useState('');

  React.useEffect(() => {
    setForm(profileFormFromUser(user));
  }, [user?.userId, user?.email, user?.phone, user?.name, user?.dob, user?.gender, user?.bloodType, user?.address]);

  const update = (key, value) => {
    setForm((f) => ({ ...f, [key]: value }));
    setStatus('');
    setErr('');
  };

  const reset = () => {
    setForm(profileFormFromUser(user));
    setStatus('');
    setErr('');
  };

  const save = async () => {
    setBusy(true);
    setErr('');
    setStatus('');
    try {
      const result = await window.molaraAuth.updatePatientProfile(form);
      if (result?.user) setForm(profileFormFromUser(result.user));
      setStatus('Profile saved to your account');
    } catch (e) {
      setErr(e.message || 'Could not save profile.');
    } finally {
      setBusy(false);
    }
  };

  const displayName = form.name || user?.name || 'Patient';
  const initials = window.molaraAuth?.initialsFor ? window.molaraAuth.initialsFor(displayName) : (user?.initials || 'PT');
  const patientId = user?.userId ? user.userId.replace(/^patient:/, 'MOL-') : 'MOL-new';
  const tabs = [
    { key: 'personal', label: 'Personal info' },
    { key: 'privacy', label: 'Privacy & data' },
    { key: 'security', label: 'Security' },
    { key: 'delete', label: 'Delete account', danger: true },
  ];
  const setPreference = (key) => setPrefs((p) => ({ ...p, [key]: !p[key] }));
  const addFamilyMember = () => {
    const value = familyDraft.trim();
    if (!value) return;
    setFamily((items) => [...items, value]);
    setFamilyDraft('');
  };
  const removeFamilyMember = (index) => setFamily((items) => items.filter((_, i) => i !== index));
  const PanelTitle = ({ title, subtitle }) => (
    <div style={{ marginBottom: 18 }}>
      <div className="ml-label" style={{ marginBottom: 6 }}>{title}</div>
      {subtitle && <p className="ml-muted" style={{ margin: 0, fontSize: 13.5, lineHeight: 1.5 }}>{subtitle}</p>}
    </div>
  );
  const settingRow = (title, sub, value, onClick) => (
    <button type="button" onClick={onClick} style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 16,
      padding: '13px 0', border: 0, borderBottom: '1px solid var(--line-2)',
      background: 'transparent', textAlign: 'left', cursor: 'pointer',
    }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13.5 }}>{title}</div>
        <div className="ml-muted" style={{ fontSize: 12 }}>{sub}</div>
      </div>
      <Toggle on={value}/>
    </button>
  );
  const activePanel = (() => {
    if (activeTab === 'personal') {
      return (
        <div className="ml-card" style={{ padding: 24 }}>
          <PanelTitle title="Personal information" subtitle="These details stay attached to your patient account and are visible to your dentist when needed."/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Field label="Full name" required value={form.name} placeholder="Your full name" onChange={(v) => update('name', v)}/>
            <Field label="Date of birth" required type="date" value={form.dob} placeholder="DD MMM YYYY" onChange={(v) => update('dob', v)}/>
            <Field label="Gender" required value={form.gender} placeholder="Female / Male / Prefer not to say" onChange={(v) => update('gender', v)}/>
            <Field label="Blood type" value={form.bloodType} placeholder="Optional" onChange={(v) => update('bloodType', v)}/>
            <Field label="Phone" value={form.phone} placeholder="Your mobile number" onChange={(v) => update('phone', v)} disabled={!!user?.phone}/>
            <Field label="Email" value={form.email} placeholder="you@gmail.com" onChange={(v) => update('email', v)} disabled={!!user?.email}/>
            <Field label="Address" required full value={form.address} placeholder="Your address" onChange={(v) => update('address', v)}/>
          </div>
          {err && <div style={{ marginTop: 14, padding: 10, borderRadius: 8, background: 'oklch(96% 0.05 25)', color: 'var(--danger)', fontSize: 12.5 }}>{err}</div>}
          {status && <div style={{ marginTop: 14, padding: 10, borderRadius: 8, background: 'oklch(94% 0.06 165)', color: 'oklch(35% 0.12 165)', fontSize: 12.5 }}>{status}</div>}
          <div style={{ marginTop: 18, display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button type="button" onClick={reset} className="ml-btn ml-btn--ghost" style={{ fontSize: 12.5 }}>Cancel</button>
            <button type="button" onClick={save} disabled={busy || !profileRequiredComplete(form)} className="ml-btn ml-btn--primary" style={{ fontSize: 12.5, opacity: (busy || !profileRequiredComplete(form)) ? 0.6 : 1 }}>{busy ? 'Saving...' : 'Save changes'}</button>
          </div>
        </div>
      );
    }
    if (activeTab === 'privacy') {
      return (
        <div className="ml-card" style={{ padding: 24 }}>
          <PanelTitle title="Privacy & data" subtitle="Molara follows an online telehealth consent approach for India: collect only what is needed, show clinical data only to the treating dentist, and keep prescription and record access inside the patient account."/>
          <div style={{ display: 'grid', gap: 12 }}>
            <InfoBlock title="Informed teleconsult consent" text="By booking, you agree to share symptoms, records, photos, and contact details for online dental guidance through text, audio, or video. Emergency symptoms should still be taken to local urgent care."/>
            <InfoBlock title="Treating dentist access" text="Only the dentist linked to your booking can see your profile details, uploaded dental records, appointment notes, and prescription for that consultation."/>
            <InfoBlock title="Data minimisation" text="Molara asks for the details needed to identify you, book the consultation, send confirmations, maintain prescriptions, and support follow-ups."/>
            <InfoBlock title="Prescription and limitations" text="Prescriptions and advice are based on the information you provide online. The dentist may recommend an in-person visit when a physical examination, X-ray, or procedure is needed."/>
            <InfoBlock title="Records, correction and deletion" text="You can download prescriptions, delete wrongly uploaded records, update profile details, and request account deletion. Some clinical records may be retained where legally or professionally required."/>
          </div>
        </div>
      );
    }
    if (activeTab === 'notifications') {
      return (
        <div className="ml-card" style={{ padding: 24 }}>
          <PanelTitle title="Notifications" subtitle="Choose which alerts Molara should send for appointments, prescriptions, and dentist messages."/>
          {settingRow('Appointment reminders', 'Email reminders before a booked consultation', prefs.reminders, () => setPreference('reminders'))}
          {settingRow('Prescription ready', 'Notify me when the dentist closes a visit and adds Rx', prefs.prescriptions, () => setPreference('prescriptions'))}
          {settingRow('Dentist messages', 'Alerts for chat and appointment updates', prefs.dentistMessages, () => setPreference('dentistMessages'))}
          {settingRow('Promotions & health tips', 'Occasional dental-care tips and Molara updates', prefs.healthTips, () => setPreference('healthTips'))}
        </div>
      );
    }
    if (activeTab === 'security') {
      return (
        <div className="ml-card" style={{ padding: 24 }}>
          <PanelTitle title="Security" subtitle="Your account is protected by one-time password sign-in through your email or phone."/>
          <div style={{ display: 'grid', gap: 12 }}>
            <InfoBlock title="Current sign-in" text={form.email ? `Email OTP: ${form.email}` : form.phone ? `Mobile OTP: ${form.phone}` : 'No email or mobile number attached yet.'}/>
            <InfoBlock title="Session protection" text="For privacy, sign out from shared devices after your consultation."/>
            <button type="button" onClick={() => window.signOutUser && window.signOutUser()} className="ml-btn ml-btn--ghost" style={{ width: 'fit-content', fontSize: 12.5 }}>Sign out</button>
          </div>
        </div>
      );
    }
    if (activeTab === 'language') {
      return (
        <div className="ml-card" style={{ padding: 24 }}>
          <PanelTitle title="Language" subtitle="Pick the language Molara should use for your patient account."/>
          <select className="ml-input" value={language} onChange={(e) => setLanguage(e.target.value)} style={{ maxWidth: 320 }}>
            <option>English (India)</option>
            <option>Hindi</option>
          </select>
          <div className="ml-muted" style={{ marginTop: 12, fontSize: 12.5 }}>This changes your local profile preference for the app screens.</div>
        </div>
      );
    }
    if (activeTab === 'family') {
      return (
        <div className="ml-card" style={{ padding: 24 }}>
          <PanelTitle title="Family members" subtitle="Add family names you may want to book dental consultations for."/>
          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            <input className="ml-input" value={familyDraft} placeholder="Family member name" onChange={(e) => setFamilyDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') addFamilyMember(); }}/>
            <button type="button" onClick={addFamilyMember} className="ml-btn ml-btn--primary" style={{ fontSize: 12.5 }}>Add</button>
          </div>
          {family.length === 0 ? (
            <div className="ml-muted" style={{ fontSize: 13 }}>No family members added yet.</div>
          ) : family.map((name, i) => (
            <div key={`${name}-${i}`} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '11px 0', borderTop: '1px solid var(--line-2)' }}>
              <span style={{ fontSize: 13.5 }}>{name}</span>
              <button type="button" onClick={() => removeFamilyMember(i)} className="ml-btn ml-btn--ghost" style={{ fontSize: 12 }}>Remove</button>
            </div>
          ))}
        </div>
      );
    }
    return (
      <div className="ml-card" style={{ padding: 24, borderColor: 'oklch(82% 0.1 25)' }}>
        <PanelTitle title="Delete account" subtitle="This is intentionally not instant. Contact Molara support before deleting account data, prescriptions, or visit history."/>
        <button type="button" className="ml-btn ml-btn--ghost" style={{ color: 'var(--danger)', borderColor: 'oklch(82% 0.1 25)', fontSize: 12.5 }}>Request account deletion</button>
      </div>
    );
  })();

  return (
    <PortalShell active="profile" title="Profile & Settings" subtitle="Manage your account, privacy and preferences">
      <div style={{ padding: '24px 32px', display: 'grid', gridTemplateColumns: '220px 1fr', gap: 32, maxWidth: 1100 }}>
        {/* Settings nav */}
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {tabs.map(n => {
            const on = activeTab === n.key;
            return (
            <button type="button" key={n.key} onClick={() => setActiveTab(n.key)} style={{
              padding: '8px 12px', borderRadius: 8, fontSize: 13.5,
              border: 0, textAlign: 'left',
              background: on ? 'var(--paper-2)' : 'transparent',
              fontWeight: on ? 500 : 400,
              color: n.danger ? 'var(--danger)' : on ? 'var(--ink)' : 'var(--ink-2)',
              cursor: 'pointer',
            }}>{n.label}</button>
          );})}
        </nav>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Avatar block */}
          <div className="ml-card" style={{ padding: 24, display: 'flex', alignItems: 'center', gap: 20 }}>
            <div className="ml-avatar" style={{ width: 80, height: 80, borderRadius: '50%', fontSize: 28 }}>{initials}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 20, fontFamily: 'var(--display)', letterSpacing: '-0.02em' }}>{displayName}</div>
              <div className="ml-muted" style={{ fontSize: 13, marginTop: 2 }}>Patient ID · {patientId}</div>
            </div>
            <button className="ml-btn ml-btn--ghost" style={{ fontSize: 12.5 }}>Change photo</button>
          </div>

          {activePanel}
        </div>
      </div>
    </PortalShell>
  );
}

function profileFormFromUser(user) {
  return {
    name: user?.name || '',
    email: user?.email || '',
    phone: user?.phone || '',
    dob: user?.dob || '',
    gender: user?.gender || '',
    bloodType: user?.bloodType || '',
    address: user?.address || '',
  };
}

function profileRequiredComplete(form) {
  return !!(String(form?.name || '').trim() && String(form?.gender || '').trim() && String(form?.dob || '').trim() && String(form?.address || '').trim());
}

function Field({ label, required, value, placeholder, full, disabled, onChange, type = 'text' }) {
  return (
    <div style={{ gridColumn: full ? 'span 2' : 'auto' }}>
      <div className="ml-label" style={{ marginBottom: 6 }}>{label} {required && <span style={{ color: 'var(--danger)' }}>*</span>}</div>
      <input className="ml-input" type={type} value={value} placeholder={placeholder || ''} disabled={disabled}
        onChange={(e) => onChange && onChange(e.target.value)}
        style={disabled ? { background: 'var(--paper-2)', color: 'var(--ink-3)' } : null}/>
    </div>
  );
}

function InfoBlock({ title, text }) {
  return (
    <div style={{ padding: 14, border: '1px solid var(--line)', borderRadius: 10, background: '#fff' }}>
      <div style={{ fontSize: 13.5, fontWeight: 500, marginBottom: 4 }}>{title}</div>
      <div className="ml-muted" style={{ fontSize: 12.5, lineHeight: 1.5 }}>{text}</div>
    </div>
  );
}

function Toggle({ on }) {
  return (
    <div style={{
      width: 36, height: 20, borderRadius: 999,
      background: on ? 'var(--blue)' : 'var(--line)',
      position: 'relative', cursor: 'pointer',
      transition: 'background .15s',
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 16, height: 16, borderRadius: 999,
        background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.2)',
        transition: 'left .15s',
      }}/>
    </div>
  );
}

window.ProfileSettings = ProfileSettings;
