// Onboarding — welcome modal (first login) + getting-started checklist.
// The checklist derives completion straight from live data (jobs, WA numbers,
// candidates, interviews), so there's no backend onboarding flag to maintain.
// Per-user localStorage flags decide who's in the onboarding cohort and when
// it's been dismissed.

const OB = {
  key(suffix) {
    const u = window.TalentirData.USER;
    const id = (u && (u.id || u.email)) || 'anon';
    return `talentir_${suffix}_${id}`;
  },
  get(suffix) { try { return localStorage.getItem(OB.key(suffix)); } catch { return null; } },
  set(suffix, v) { try { localStorage.setItem(OB.key(suffix), v); } catch { /* private mode */ } },
};
window.Onboarding = OB;

// Single source of truth for the four core first-run steps. `done` is computed
// from the live counts the caller passes in.
function onboardingSteps(counts) {
  return [
    { id: 'job',  icon: 'briefcase', label: 'Buat lowongan pertama', desc: 'Posisi + halaman publik dibuat otomatis', cta: 'Buat',       to: { view: 'jobs', subview: 'new' }, done: counts.jobs > 0 },
    { id: 'wa',   icon: 'message',   label: 'Aktifkan WhatsApp Bot',  desc: 'Bot menyaring & menjawab pelamar otomatis', cta: 'Hubungkan', to: { view: 'whatsapp' },             done: counts.wa > 0 },
    { id: 'cand', icon: 'users',     label: 'Tambah kandidat',        desc: 'Import CSV/Excel atau tambah manual',       cta: 'Tambah',    to: { view: 'import' },               done: counts.cands > 0 },
    { id: 'iv',   icon: 'clock',     label: 'Jadwalkan wawancara',    desc: 'Atur jadwal & penanggung jawab di Kalender', cta: 'Jadwalkan', to: { view: 'calendar' },            done: counts.interviews > 0 },
  ];
}

// Shown once to fresh accounts right after the first login.
function OnboardingWelcome({ onClose, go }) {
  const steps = onboardingSteps({ jobs: 0, wa: 0, cands: 0, interviews: 0 });
  const start = () => { onClose(); go({ view: 'jobs', subview: 'new' }); };

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal ob-welcome" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head" style={{ justifyContent: 'space-between' }}>
          <div className="row-flex" style={{ gap: 10 }}>
            <div className="ob-mark">T</div>
            <strong style={{ fontSize: 16 }}>Selamat datang di Talentir 👋</strong>
          </div>
          <button className="btn icon ghost" onClick={onClose} title="Tutup"><Icon name="x" size={16}/></button>
        </div>
        <div className="modal-body">
          <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>
            Talentir adalah <strong>ATS bertenaga AI</strong> yang menyaring pelamar otomatis lewat WhatsApp.
            Empat langkah berikut akan menyiapkan akun Anda untuk mulai merekrut:
          </p>
          <div className="ob-steps">
            {steps.map((s, i) => (
              <div key={s.id} className="ob-step-intro">
                <div className="ob-num">{i + 1}</div>
                <div className="ico"><Icon name={s.icon} size={16}/></div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13.5 }}>{s.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--muted)' }}>{s.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn ghost" onClick={onClose}>Lewati</button>
          <button className="btn primary" onClick={start}>Mulai <Icon name="arrow" size={14}/></button>
        </div>
      </div>
    </div>
  );
}

// Persistent card on the Dashboard. Renders only for accounts in the onboarding
// cohort (ob_active) that haven't dismissed it (ob_done).
function OnboardingChecklist({ go, counts }) {
  const [hidden, setHidden] = useState(() => OB.get('ob_done') === '1');
  if (OB.get('ob_active') !== '1' || hidden) return null;

  const steps = onboardingSteps(counts);
  const done = steps.filter((s) => s.done).length;
  const total = steps.length;
  const allDone = done === total;
  const dismiss = () => { OB.set('ob_done', '1'); setHidden(true); };

  return (
    <div className="card ob-card">
      <div className="ob-card-head">
        <div>
          <div className="ob-title"><Icon name="sparkles" size={14}/> {allDone ? 'Setup selesai 🎉' : 'Mulai di sini'}</div>
          <div className="ob-sub">
            {allDone
              ? 'Semua langkah beres. Selamat merekrut bersama Talentir!'
              : `${done}/${total} langkah selesai — selesaikan untuk memaksimalkan Talentir`}
          </div>
        </div>
        <button className="btn ghost sm" onClick={dismiss}>{allDone ? 'Tutup' : 'Sembunyikan'}</button>
      </div>

      <div className="ob-progress"><div className="bar" style={{ width: `${(done / total) * 100}%` }}/></div>

      {!allDone && (
        <div className="ob-list">
          {steps.map((s) => (
            <div key={s.id} className={'ob-step ' + (s.done ? 'done' : '')}>
              <div className="ob-check">
                {s.done ? <Icon name="check" size={13} stroke={2.6}/> : <Icon name={s.icon} size={14}/>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="ob-step-label">{s.label}</div>
                <div className="ob-step-desc">{s.desc}</div>
              </div>
              {s.done
                ? <span className="badge good"><Icon name="check" size={10} stroke={2.6}/>Selesai</span>
                : <button className="btn sm primary" onClick={() => go(s.to)}>{s.cta} <Icon name="chevron" size={12}/></button>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.OnboardingWelcome = OnboardingWelcome;
window.OnboardingChecklist = OnboardingChecklist;
