// Moderis App — Profiel.
// Fitness-data (lengte, gewicht, leeftijd, geslacht, activiteit, doel,
// intensiteit) + dagdoelen. Volgt de Forest-design-taal van pantry.
//
// "Bereken doelen voor mij" stuurt auto_macros: true mee zodat de backend
// kcal/eiwit/koolh/vet doelen herberekent via Mifflin-St Jeor.

const DOEL_OPTIES = [
  { id: 'afvallen',    label: 'Afvallen',     hint: 'kcal-tekort, eiwit hoog' },
  { id: 'cut',         label: 'Cut',          hint: 'strak tekort, spier behouden' },
  { id: 'onderhoud',   label: 'Onderhoud',    hint: 'gewicht stabiel' },
  { id: 'lean_bulk',   label: 'Lean bulk',    hint: 'klein overschot, weinig vet' },
  { id: 'spieropbouw', label: 'Spieropbouw',  hint: 'overschot, max spiergroei' },
];

const ACT_OPTIES = [
  { id: 'tracker',     label: 'Tracker',      hint: 'beweging komt van je tracker — aangeraden als je hem altijd draagt' },
  { id: 'sedentair',   label: 'Sedentair',    hint: 'kantoor, weinig beweging' },
  { id: 'licht',       label: 'Licht',        hint: '1–3× sport per week' },
  { id: 'matig',       label: 'Matig',        hint: '3–5× sport per week' },
  { id: 'actief',      label: 'Actief',       hint: '6–7× sport per week' },
  { id: 'zeer_actief', label: 'Zeer actief',  hint: 'fysiek werk + dagelijks sport' },
];

const INTENS_OPTIES = [
  { id: 'langzaam',  label: 'Langzaam' },
  { id: 'gemiddeld', label: 'Gemiddeld' },
  { id: 'agressief', label: 'Agressief' },
];

const GESLACHT_OPTIES = [
  { id: 'man',    label: 'Man' },
  { id: 'vrouw',  label: 'Vrouw' },
  { id: 'anders', label: 'Anders' },
];

function ProfileField({ label, hint, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
        <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--forest-900)' }}>{label}</span>
        {hint && <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{hint}</span>}
      </div>
      {children}
    </div>
  );
}

function ProfileInput({ value, onChange, type = 'text', suffix, placeholder, step }) {
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center',
      background: 'var(--m-card)', border: '1px solid var(--m-line)', borderRadius: 12 }}>
      <input
        type={type} step={step} value={value ?? ''} placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        style={{ flex: 1, padding: '11px 13px', fontSize: 14, background: 'transparent',
          border: 'none', outline: 'none', color: 'var(--forest-950)', fontFamily: 'inherit',
          minWidth: 0 }}
      />
      {suffix && (
        <span className="num" style={{ paddingRight: 13, fontSize: 12, color: 'var(--ink-3)' }}>
          {suffix}
        </span>
      )}
    </div>
  );
}

function PillSelect({ options, value, onChange, columns = 0 }) {
  // Vaste kolommen (bv. 3) voor korte labels; anders een responsieve grid die
  // op mobiel 1 kolom is (geen losse knop onderaan) en op breed meerdere.
  return (
    <div className={columns ? '' : 'm-pill-grid'}
      style={columns ? { display: 'grid', gap: 8, gridTemplateColumns: `repeat(${columns}, 1fr)` } : undefined}>
      {options.map((opt) => {
        const active = value === opt.id;
        return (
          <button key={opt.id} type="button" className="tap" onClick={() => onChange(opt.id)}
            style={{
              padding: '10px 12px', borderRadius: 12, textAlign: 'left',
              border: '1px solid ' + (active ? 'var(--forest-600)' : 'var(--m-line)'),
              background: active ? 'var(--forest-100)' : 'var(--m-card)',
              color: 'var(--forest-950)', cursor: 'pointer',
              boxShadow: active ? '0 0 0 3px var(--forest-100)' : 'none',
              transition: 'all .15s ease',
            }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{opt.label}</div>
            {opt.hint && (
              <div style={{ fontSize: 11, color: active ? 'var(--forest-700)' : 'var(--ink-3)', marginTop: 2 }}>
                {opt.hint}
              </div>
            )}
          </button>
        );
      })}
    </div>
  );
}

function ProfileScreen({ profiel, fitbit, onSave, onClose }) {
  const [form, setForm] = React.useState(() => ({
    naam:              profiel?.naam              || '',
    geslacht:          profiel?.geslacht          || '',
    geboortedatum:     profiel?.geboortedatum     || '',
    lengte_cm:         profiel?.lengte_cm         ?? '',
    gewicht_kg:        profiel?.gewicht_kg        ?? '',
    activiteitsniveau: profiel?.activiteitsniveau || 'matig',
    doel:              profiel?.doel              || 'onderhoud',
    doel_intensiteit:  profiel?.doel_intensiteit  || 'gemiddeld',
    kcal_doel:         profiel?.kcal_doel         ?? '',
    eiwitten_doel:     profiel?.eiwitten_doel     ?? '',
    koolhydraten_doel: profiel?.koolhydraten_doel ?? '',
    vetten_doel:       profiel?.vetten_doel       ?? '',
    bedtijd:           profiel?.bedtijd           || '23:00',
    eten_tot:          profiel?.eten_tot          || '19:30',
  }));
  const [busy, setBusy] = React.useState(false);
  const set = (k) => (v) => setForm((f) => ({ ...f, [k]: v }));

  const heeftBodyData = form.lengte_cm && form.gewicht_kg && form.geboortedatum && form.geslacht;

  const save = async (auto) => {
    if (busy) return;
    setBusy(true);
    try {
      await onSave({ ...form, auto_macros: !!auto });
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="screen screen-profile">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
        <div>
          <span className="m-eyebrow">Over jou</span>
          <h1 style={{ margin: '4px 0 0', fontFamily: 'var(--m-serif)', fontSize: 28, fontWeight: 500,
            letterSpacing: '-0.015em', color: 'var(--forest-950)' }}>Profiel</h1>
        </div>
        {onClose && (
          <button className="m-btn tap" onClick={onClose}
            style={{ width: 36, height: 36, padding: 0, borderRadius: 11,
              background: 'var(--m-card-2)', border: '1px solid var(--m-line)' }}>
            <MIcon name="close" size={15} color="var(--ink-2)" />
          </button>
        )}
      </div>

      {/* Basis */}
      <div style={{ background: 'var(--m-card)', border: '1px solid var(--m-line)',
        borderRadius: 18, padding: '16px 16px 6px', marginBottom: 14, boxShadow: 'var(--m-shadow)' }}>
        <div className="m-eyebrow" style={{ marginBottom: 10 }}>Basis</div>
        <ProfileField label="Naam">
          <ProfileInput value={form.naam} onChange={set('naam')} placeholder="Voornaam" />
        </ProfileField>
        <ProfileField label="Geslacht" hint="voor BMR-berekening">
          <PillSelect options={GESLACHT_OPTIES} value={form.geslacht} onChange={set('geslacht')} columns={3} />
        </ProfileField>
        <ProfileField label="Geboortedatum">
          <ProfileInput type="date" value={form.geboortedatum} onChange={set('geboortedatum')} />
        </ProfileField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <ProfileField label="Lengte">
            <ProfileInput type="number" step="1" value={form.lengte_cm} onChange={set('lengte_cm')} suffix="cm" />
          </ProfileField>
          <ProfileField label="Gewicht">
            <ProfileInput type="number" step="0.1" value={form.gewicht_kg} onChange={set('gewicht_kg')} suffix="kg" />
          </ProfileField>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <ProfileField label="Avondeten uiterlijk" hint="laatste eetmoment van je schema">
            <ProfileInput type="time" value={form.eten_tot} onChange={set('eten_tot')} />
          </ProfileField>
          <ProfileField label="Bedtijd" hint="vangnet: nooit later dan 2u voor bed">
            <ProfileInput type="time" value={form.bedtijd} onChange={set('bedtijd')} />
          </ProfileField>
        </div>
      </div>

      {/* Activiteit */}
      <div style={{ background: 'var(--m-card)', border: '1px solid var(--m-line)',
        borderRadius: 18, padding: '16px 16px', marginBottom: 14, boxShadow: 'var(--m-shadow)' }}>
        <div className="m-eyebrow" style={{ marginBottom: 10 }}>Activiteitsniveau</div>
        <PillSelect options={ACT_OPTIES} value={form.activiteitsniveau} onChange={set('activiteitsniveau')} />
      </div>

      {/* Doel */}
      <div style={{ background: 'var(--m-card)', border: '1px solid var(--m-line)',
        borderRadius: 18, padding: '16px 16px', marginBottom: 14, boxShadow: 'var(--m-shadow)' }}>
        <div className="m-eyebrow" style={{ marginBottom: 10 }}>Fitnessdoel</div>
        <PillSelect options={DOEL_OPTIES} value={form.doel} onChange={set('doel')} />
        <div style={{ marginTop: 14 }}>
          <div className="m-eyebrow" style={{ marginBottom: 8 }}>Intensiteit</div>
          <PillSelect options={INTENS_OPTIES} value={form.doel_intensiteit} onChange={set('doel_intensiteit')} columns={3} />
        </div>
      </div>

      {/* Dagdoelen */}
      <div style={{ background: 'var(--m-card)', border: '1px solid var(--m-line)',
        borderRadius: 18, padding: '16px 16px', marginBottom: 14, boxShadow: 'var(--m-shadow)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
          <span className="m-eyebrow">Dagdoelen</span>
          <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>handmatig of laten berekenen</span>
        </div>
        <ProfileField label="Calorieën">
          <ProfileInput type="number" step="10" value={form.kcal_doel} onChange={set('kcal_doel')} suffix="kcal" />
        </ProfileField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          <ProfileField label="Eiwit">
            <ProfileInput type="number" step="1" value={form.eiwitten_doel} onChange={set('eiwitten_doel')} suffix="g" />
          </ProfileField>
          <ProfileField label="Koolh.">
            <ProfileInput type="number" step="1" value={form.koolhydraten_doel} onChange={set('koolhydraten_doel')} suffix="g" />
          </ProfileField>
          <ProfileField label="Vet">
            <ProfileInput type="number" step="1" value={form.vetten_doel} onChange={set('vetten_doel')} suffix="g" />
          </ProfileField>
        </div>
        <button type="button" className="m-btn tap" disabled={!heeftBodyData || busy} onClick={() => save(true)}
          style={{
            width: '100%', marginTop: 6, padding: '12px', fontSize: 13,
            background: heeftBodyData ? 'var(--forest-100)' : 'var(--m-card-2)',
            border: '1px solid ' + (heeftBodyData ? 'var(--forest-200)' : 'var(--m-line)'),
            color: heeftBodyData ? 'var(--forest-700)' : 'var(--ink-3)',
            borderRadius: 12, cursor: heeftBodyData && !busy ? 'pointer' : 'not-allowed',
          }}>
          <MIcon name="spark" size={15} color={heeftBodyData ? 'var(--forest-600)' : 'var(--ink-3)'} />
          {heeftBodyData ? 'Bereken mijn doelen via Moderis' : 'Vul lengte, gewicht, leeftijd en geslacht in'}
        </button>
      </div>

      <button type="button" className="m-btn m-btn-primary tap" disabled={busy} onClick={() => save(false)}
        style={{ width: '100%', padding: '14px', fontSize: 14, marginBottom: 14 }}>
        {busy ? <Spinner size={16} /> : <MIcon name="check" size={16} sw={2.2} color="var(--on-forest)" />}
        {busy ? 'Opslaan…' : 'Opslaan'}
      </button>

      <GoogleHealthSection fitbit={fitbit} />

      <button type="button" className="m-btn m-btn-ghost tap"
        onClick={async () => { try { await window.moderisAuth.signOut(); } catch {} }}
        style={{ width: '100%', padding: '12px', fontSize: 13, marginTop: 14, marginBottom: 24,
          color: 'var(--ink-2)' }}>
        <MIcon name="close" size={14} color="var(--ink-2)" /> Uitloggen
      </button>
    </div>
  );
}

// ── Google Health-koppeling: status + Herkoppel-knop ───────────────────
function GoogleHealthSection({ fitbit }) {
  // Drie statussen:
  //   revoked  — token werkt niet meer, gebruiker moet OAuth opnieuw doen
  //   linked   — fitbit heeft echte data (stappen-veld bestaat)
  //   loading  — fitbit nog null (zou hier nauwelijks zichtbaar zijn)
  let status = 'loading';
  if (fitbit?._googleRevoked) status = 'revoked';
  else if (fitbit && (fitbit.stappen != null || fitbit.bron === 'cache')) status = 'linked';
  else if (fitbit && Object.keys(fitbit).length === 0) status = 'revoked'; // lege fail-state

  const dotColor = status === 'linked'  ? 'var(--leaf)'
                 : status === 'revoked' ? 'var(--macro-fat)'
                 : 'var(--ink-3)';
  const titel = status === 'linked'  ? 'Verbonden met Google Health'
              : status === 'revoked' ? 'Google-koppeling vervallen'
              : 'Google Health';
  const subtitel = status === 'linked'
    ? 'Stappen, slaap en hartslag komen automatisch binnen.'
    : status === 'revoked'
      ? 'Herkoppel om je activiteitsdata weer in te laden.'
      : 'Status wordt opgehaald…';

  const herkoppel = async () => {
    try { await window.moderisAuth.signIn(); }
    catch (err) { console.error('signIn fail:', err); }
  };

  return (
    <div style={{ background: 'var(--m-card)', border: '1px solid var(--m-line)',
      borderRadius: 18, padding: '16px', boxShadow: 'var(--m-shadow)' }}>
      <div className="m-eyebrow" style={{ marginBottom: 12 }}>Google Health</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: status === 'revoked' ? 14 : 0 }}>
        <span style={{ width: 9, height: 9, borderRadius: 999, background: dotColor,
          boxShadow: `0 0 0 4px ${dotColor === 'var(--leaf)' ? 'rgba(139,194,74,0.18)' : 'rgba(192,106,68,0.14)'}`,
          flex: '0 0 auto' }}></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--forest-950)' }}>{titel}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{subtitel}</div>
        </div>
      </div>
      {status === 'revoked' && (
        <button type="button" className="m-btn m-btn-primary tap" onClick={herkoppel}
          style={{ width: '100%', padding: '12px', fontSize: 13 }}>
          <MIcon name="spark" size={15} color="var(--on-forest)" />
          Herkoppel met Google
        </button>
      )}
    </div>
  );
}

Object.assign(window, { ProfileScreen });
