// First-Month Wizard — main app
// Reads window.FMW_TASKS + window.FMW_CATEGORIES from fmw-tasks.js

const { useState, useEffect, useMemo, useRef } = React;

const STORAGE_KEY = 'nri-fmw-v1';
const loadState = () => {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}; }
  catch { return {}; }
};
const saveState = (s) => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch {} };

const todayISO = () => new Date().toISOString().slice(0, 10);
const daysBetween = (a, b) => Math.floor((new Date(b) - new Date(a)) / 86400000);
const addDays = (iso, d) => {
  const dt = new Date(iso);
  dt.setDate(dt.getDate() + d);
  return dt.toISOString().slice(0, 10);
};
const fmtDate = (iso) => {
  if (!iso) return '';
  return new Date(iso + 'T12:00:00').toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
};

// ─── filter task templates against a profile ────────────────────────────────
function tasksForProfile(profile) {
  return window.FMW_TASKS.filter(t => {
    if (t.countries && t.countries.length && !t.countries.includes(profile.country)) return false;
    if (t.visas && t.visas.length && !t.visas.includes('all') && !t.visas.includes(profile.role)) return false;
    return true;
  }).map(t => ({
    ...t,
    dueDate: profile.arrivalDate ? addDays(profile.arrivalDate, t.day - 1) : null,
    links: (t.links || []).filter(l => !l.country || l.country === profile.country),
  }));
}

// ═══════════════════════════════════════════════════════════════════════════
// SETUP WIZARD
// ═══════════════════════════════════════════════════════════════════════════

function SetupWizard({ initial, onComplete }) {
  const [step, setStep] = useState(0);
  const [profile, setProfile] = useState(initial || {
    name: '', country: '', city: '', role: '', visaType: '',
    arrivalDate: todayISO(), school: '', origin: '',
  });
  const set = (k, v) => setProfile(p => ({ ...p, [k]: v }));

  const steps = ['Hello', 'Where', 'Status', 'When', 'A few more details'];

  const canAdvance = () => {
    if (step === 0) return profile.name.trim().length > 0;
    if (step === 1) return profile.country && profile.city.trim();
    if (step === 2) return profile.role;
    if (step === 3) return profile.arrivalDate;
    return true;
  };

  const next = () => {
    if (step === steps.length - 1) onComplete(profile);
    else setStep(step + 1);
  };
  const back = () => setStep(Math.max(0, step - 1));

  return (
    <div className="setup">
      <div className="setup-progress">
        {steps.map((_, i) => (
          <div key={i} className={'sp-dot ' + (i < step ? 'done' : i === step ? 'active' : '')} />
        ))}
      </div>

      <div className="setup-step" key={step}>
        {step === 0 && (
          <>
            <div className="step-eyebrow">Welcome · Step 1 of 5</div>
            <h1 className="step-title">Let's make your <em>first month</em> easier.</h1>
            <p className="step-sub">Tell us a few things and we'll generate a personalized 30-day plan with deadlines, links, and just the tasks that apply to you. Free, stored only on this device.</p>
            <div className="form-row">
              <label className="form-label">What should we call you?</label>
              <input
                className="form-input"
                placeholder="First name"
                value={profile.name}
                onChange={e => set('name', e.target.value)}
                autoFocus
              />
            </div>
          </>
        )}

        {step === 1 && (
          <>
            <div className="step-eyebrow">Step 2 of 5</div>
            <h1 className="step-title">Where are you <em>landing</em>?</h1>
            <p className="step-sub">Different country, different banks, different SSN/SIN, different everything.</p>
            <div className="form-row">
              <label className="form-label">Country</label>
              <div className="choice-grid cols-2">
                <button className={'choice ' + (profile.country === 'us' ? 'active' : '')} onClick={() => set('country', 'us')}>
                  <div className="choice-flag">🇺🇸</div>
                  <div className="choice-title">United States</div>
                  <div className="choice-sub">SSN, ACA, 1040-NR / 1040</div>
                </button>
                <button className={'choice ' + (profile.country === 'ca' ? 'active' : '')} onClick={() => set('country', 'ca')}>
                  <div className="choice-flag">🇨🇦</div>
                  <div className="choice-title">Canada</div>
                  <div className="choice-sub">SIN, MSP/OHIP, T1 / T2202</div>
                </button>
              </div>
            </div>
            <div className="form-row">
              <label className="form-label">City you're moving to</label>
              <input
                className="form-input"
                placeholder="e.g. Toronto, NYC, San Francisco"
                value={profile.city}
                onChange={e => set('city', e.target.value)}
              />
            </div>
          </>
        )}

        {step === 2 && (
          <>
            <div className="step-eyebrow">Step 3 of 5</div>
            <h1 className="step-title">What brings you <em>here</em>?</h1>
            <p className="step-sub">Your status decides which tasks show up — F1 students get SEVIS check-in, workers skip it.</p>
            <div className="form-row">
              <div className="choice-grid">
                {[
                  { id: 'student', emoji: '🎓', title: 'Student', sub: 'F1 (US) / Study permit (CA)' },
                  { id: 'worker', emoji: '💼', title: 'Working professional', sub: 'H1B, L1, O / Work permit, PGWP' },
                  { id: 'visitor', emoji: '✈️', title: 'Visiting family', sub: 'B1/B2, Visitor visa, Super Visa' },
                  { id: 'settled', emoji: '🏡', title: 'Just moved as PR', sub: 'Green card / PR landing' },
                ].map(r => (
                  <button key={r.id} className={'choice ' + (profile.role === r.id ? 'active' : '')} onClick={() => set('role', r.id)}>
                    <div className="choice-emoji">{r.emoji}</div>
                    <div className="choice-title">{r.title}</div>
                    <div className="choice-sub">{r.sub}</div>
                  </button>
                ))}
              </div>
            </div>
          </>
        )}

        {step === 3 && (
          <>
            <div className="step-eyebrow">Step 4 of 5</div>
            <h1 className="step-title">When are you <em>arriving</em>?</h1>
            <p className="step-sub">We'll turn this into a day-by-day plan with real dates and deadlines.</p>
            <div className="form-row">
              <label className="form-label">Arrival date</label>
              <input
                className="form-input"
                type="date"
                value={profile.arrivalDate}
                onChange={e => set('arrivalDate', e.target.value)}
                style={{ maxWidth: 280 }}
              />
              <div style={{ marginTop: 12, fontSize: 13, color: 'var(--ink-3)' }}>
                Past date works too — already arrived? We'll mark earlier days as overdue.
              </div>
            </div>
          </>
        )}

        {step === 4 && (
          <>
            <div className="step-eyebrow">Step 5 of 5 · Optional</div>
            <h1 className="step-title">A bit more <em>context</em>.</h1>
            <p className="step-sub">Helps us tailor links and tips. Both fields are optional — skip if you want.</p>
            <div className="form-row">
              <label className="form-label">{profile.role === 'student' ? 'School / University' : 'Employer / Company'}</label>
              <input
                className="form-input"
                placeholder={profile.role === 'student' ? 'e.g. NYU, University of Toronto' : 'e.g. Google, RBC'}
                value={profile.school}
                onChange={e => set('school', e.target.value)}
              />
            </div>
            <div className="form-row">
              <label className="form-label">Which region of India are you from? <span style={{ color: 'var(--ink-3)' }}>(for food/community tips)</span></label>
              <select className="form-select" value={profile.origin} onChange={e => set('origin', e.target.value)}>
                <option value="">Prefer not to say</option>
                <option value="north">North (Delhi, Punjab, UP, Haryana, HP)</option>
                <option value="south">South (TN, KA, KL, AP, TG)</option>
                <option value="west">West (MH, GJ, GA, RJ)</option>
                <option value="east">East (WB, OD, BR, JH)</option>
                <option value="northeast">Northeast (AS, MN, ML, NL, MZ, AR, TR, SK)</option>
              </select>
            </div>
          </>
        )}
      </div>

      <div className="setup-actions">
        {step > 0
          ? <button className="btn btn-ghost" onClick={back}>← Back</button>
          : <a href="/" className="btn-link">← Back to NRI Outpost</a>}
        <button className="btn btn-primary" onClick={next} disabled={!canAdvance()}>
          {step === steps.length - 1 ? 'Generate my plan →' : 'Continue →'}
        </button>
      </div>
    </div>
  );
}

window.SetupWizard = SetupWizard;
window.tasksForProfile = tasksForProfile;
window.fmwHelpers = { todayISO, daysBetween, addDays, fmtDate };
