// Post-signup onboarding: consent screen, then optional profile wizard.
//
// Mounted by App as <OnboardingGate user={user} />. On user change it asks
// the server for the current consent record. If none exists (user has neither
// accepted nor declined), it shows the modal. Once the user accepts/declines
// or completes/skips the wizard, it stays out of the way until the next
// fresh signup (i.e. forever, unless the user wipes their account).

const ONBOARD_OVERLAY = {
  position: 'fixed', inset: 0, zIndex: 1100,
  background: 'rgba(0,0,0,0.86)', backdropFilter: 'blur(6px)',
  display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
};
const ONBOARD_PANEL = {
  position: 'relative', width: '100%', maxWidth: 480,
  background: '#0a0a0a', border: '1px solid #222', borderRadius: 8,
  padding: 32, color: '#fff',
};
const SECTION_LABEL = { fontSize: 11, letterSpacing: '0.3em', color: 'var(--accent)' };
const HEADLINE = { fontSize: 'clamp(34px, 5vw, 48px)', lineHeight: 1, marginTop: 12 };
const LEAD = { color: 'rgba(255,255,255,0.65)', fontSize: 14, lineHeight: 1.55, marginTop: 14 };
const FIELD_LABEL = { fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.55)', textTransform: 'uppercase' };
const INPUT = {
  width: '100%', padding: '12px 14px', marginTop: 8,
  background: '#141414', border: '1px solid #2a2a2a', borderRadius: 4,
  color: '#fff', fontFamily: 'Archivo', fontSize: 15, boxSizing: 'border-box',
};
const SELECT = { ...INPUT, appearance: 'none' };
const PRIMARY_BTN = (disabled = false) => ({
  marginTop: 18, width: '100%', padding: '14px 20px',
  background: '#fff', color: '#0a0a0a', border: 0, borderRadius: 4,
  fontFamily: 'Archivo', fontWeight: 800, fontSize: 14, letterSpacing: '0.06em',
  textTransform: 'uppercase', cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.55 : 1,
});
const SECONDARY_BTN = {
  marginTop: 12, width: '100%', padding: '12px 20px',
  background: 'transparent', color: '#fff', border: '1px solid rgba(255,255,255,0.25)', borderRadius: 4,
  fontFamily: 'Archivo', fontWeight: 700, fontSize: 13, letterSpacing: '0.06em', textTransform: 'uppercase',
  cursor: 'pointer',
};
const SKIP_LINK = {
  marginTop: 14, textAlign: 'center', fontSize: 12,
  color: 'rgba(255,255,255,0.55)', cursor: 'pointer',
  textDecoration: 'underline',
};
const ROW_2 = { display: 'grid', gridTemplateColumns: '1fr 110px', gap: 10 };

const CONSENT_BLURB = [
  "We can tailor your WODs using a few private profile facts: your age, gender, weight, and height.",
  "What we store: only what you enter, on your account, on Cloudflare D1. We don't share it with other users and never use it for cross-account learning.",
  "Where it goes: a structured summary (e.g. age in years and weight in kg) is sent to OpenAI alongside your messages. We never send your date of birth raw.",
  "You can edit or wipe everything from your profile page anytime.",
];

function OnboardingGate({ user }) {
  const [stage, setStage] = React.useState('hidden'); // hidden | consent | wizard | done
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);

  // Wizard fields.
  const [dob, setDob] = React.useState('');
  const [gender, setGender] = React.useState('');
  const [weightVal, setWeightVal] = React.useState('');
  const [weightUnit, setWeightUnit] = React.useState('kg');
  const [heightVal, setHeightVal] = React.useState('');
  const [heightUnit, setHeightUnit] = React.useState('cm');

  // On user change, check whether we already have a consent record.
  React.useEffect(() => {
    if (!user) { setStage('hidden'); return; }
    let cancelled = false;
    (async () => {
      try {
        const d = await window.SnatchAPI.getConsent();
        if (cancelled) return;
        // Show only when no consent record exists at all (created_at is null).
        const recorded = d?.consent?.created_at != null;
        setStage(recorded ? 'hidden' : 'consent');
      } catch {
        if (!cancelled) setStage('hidden');
      }
    })();
    return () => { cancelled = true; };
  }, [user]);

  if (stage === 'hidden' || stage === 'done') return null;

  const acceptConsent = async () => {
    setBusy(true); setError(null);
    try {
      await window.SnatchAPI.recordConsent(true);
      setStage('wizard');
    } catch (e) {
      setError(e.message || 'Could not save consent.');
    } finally {
      setBusy(false);
    }
  };

  const declineConsent = async () => {
    setBusy(true); setError(null);
    try {
      await window.SnatchAPI.recordConsent(false);
      setStage('done');
    } catch (e) {
      setError(e.message || 'Could not save consent.');
    } finally {
      setBusy(false);
    }
  };

  const skipWizard = () => setStage('done');

  const saveWizard = async () => {
    const fields = {};
    if (dob) fields.date_of_birth = dob;
    if (gender) fields.gender = gender;
    if (weightVal) {
      const n = Number(weightVal);
      if (!Number.isFinite(n) || n <= 0) { setError('Body weight must be a positive number.'); return; }
      fields.body_weight_value = n;
      fields.body_weight_unit = weightUnit;
    }
    if (heightVal) {
      const n = Number(heightVal);
      if (!Number.isFinite(n) || n <= 0) { setError('Body height must be a positive number.'); return; }
      fields.body_height_value = n;
      fields.body_height_unit = heightUnit;
    }
    if (Object.keys(fields).length === 0) { skipWizard(); return; }

    setBusy(true); setError(null);
    try {
      await window.SnatchAPI.patchPersonalProfile(fields);
      setStage('done');
    } catch (e) {
      setError(e.message || 'Could not save profile.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={ONBOARD_OVERLAY}>
      <div style={ONBOARD_PANEL} onClick={(e) => e.stopPropagation()}>
        {stage === 'consent' && (
          <>
            <div className="mono" style={SECTION_LABEL}>● PERSONALIZATION</div>
            <div className="display" style={HEADLINE}>Make your<br />WODs yours.</div>
            {CONSENT_BLURB.map((p, i) => (
              <p key={i} style={LEAD}>{p}</p>
            ))}
            {error && <ErrorBox>{error}</ErrorBox>}
            <button onClick={acceptConsent} disabled={busy} style={PRIMARY_BTN(busy)}>
              {busy ? 'Saving…' : 'Yes, personalize my WODs'}
            </button>
            <button onClick={declineConsent} disabled={busy} style={SECONDARY_BTN}>
              No thanks, keep them generic
            </button>
            <div className="mono" style={{ marginTop: 14, fontSize: 10, opacity: 0.4, letterSpacing: '0.18em', textAlign: 'center' }}>
              YOU CAN CHANGE THIS LATER IN PROFILE
            </div>
          </>
        )}

        {stage === 'wizard' && (
          <>
            <div className="mono" style={SECTION_LABEL}>● ABOUT YOU (OPTIONAL)</div>
            <div className="display" style={HEADLINE}>Tell coach<br />a bit about you.</div>
            <p style={LEAD}>Skip any field. You can fill or change everything later.</p>

            <div style={{ marginTop: 24 }}>
              <label style={FIELD_LABEL}>Date of birth</label>
              <input
                type="date" value={dob} onChange={(e) => setDob(e.target.value)}
                style={INPUT}
              />
            </div>
            <div style={{ marginTop: 16 }}>
              <label style={FIELD_LABEL}>Gender</label>
              <input
                type="text" value={gender} onChange={(e) => setGender(e.target.value)}
                placeholder="e.g. female / male / nonbinary"
                style={INPUT} maxLength={40}
              />
            </div>
            <div style={{ marginTop: 16 }}>
              <label style={FIELD_LABEL}>Body weight</label>
              <div style={ROW_2}>
                <input
                  type="number" inputMode="decimal" min="1" step="0.1"
                  value={weightVal} onChange={(e) => setWeightVal(e.target.value)}
                  placeholder="e.g. 78"
                  style={INPUT}
                />
                <select value={weightUnit} onChange={(e) => setWeightUnit(e.target.value)} style={SELECT}>
                  <option value="kg">kg</option>
                  <option value="lb">lb</option>
                </select>
              </div>
            </div>
            <div style={{ marginTop: 16 }}>
              <label style={FIELD_LABEL}>Body height</label>
              <div style={ROW_2}>
                <input
                  type="number" inputMode="decimal" min="1" step="0.1"
                  value={heightVal} onChange={(e) => setHeightVal(e.target.value)}
                  placeholder="e.g. 178"
                  style={INPUT}
                />
                <select value={heightUnit} onChange={(e) => setHeightUnit(e.target.value)} style={SELECT}>
                  <option value="cm">cm</option>
                  <option value="inch">inch</option>
                </select>
              </div>
            </div>

            {error && <ErrorBox>{error}</ErrorBox>}

            <button onClick={saveWizard} disabled={busy} style={PRIMARY_BTN(busy)}>
              {busy ? 'Saving…' : 'Save and continue'}
            </button>
            <div onClick={skipWizard} style={SKIP_LINK}>Skip — I'll do this later</div>
          </>
        )}
      </div>
    </div>
  );
}

function ErrorBox({ children }) {
  return (
    <div style={{ marginTop: 16, padding: 12, border: '1px solid rgba(255,45,45,0.35)', background: 'rgba(255,45,45,0.08)', color: '#fca', fontSize: 13, lineHeight: 1.45, borderRadius: 4 }}>
      {children}
    </div>
  );
}

window.OnboardingGate = OnboardingGate;
