// ============ ONBOARDING WIZARD ============
// First-run questionnaire. Fires once per tenant — when the dashboard
// detects no agents AND no saved profile. The answers go to
// /onboarding/intake where Claude turns them into a structured company
// profile + 3–5 recommended agents.
//
// Six questions in six steps, plus a final review screen with the
// recommended agents pre-filled and a one-click "Hire" button. Owners
// can skip — they'll see a Settings prompt later. Once completed, the
// `onboardingCompletedAt` flag on the tenant config means it never
// auto-fires again (open from Settings → Danger zone to re-run).

const SERVER_URL_OB = () =>
  (typeof window !== "undefined" && window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) || "";

const VOICE_OPTIONS = [
  { id: "warm",    label: "Warm",    note: "Friendly. Uses first names. Quick to reassure." },
  { id: "direct",  label: "Direct",  note: "Short, clear sentences. No fluff." },
  { id: "formal", label: "Formal",   note: "Polite, structured. Suits regulated industries." },
  { id: "playful", label: "Playful", note: "Witty, light. Pop-culture okay. Emojis sparingly." },
];

const USE_CASES = [
  { id: "answer-faqs",         label: "Answer FAQs",                   icon: "💬" },
  { id: "capture-leads",       label: "Capture leads",                 icon: "✦"  },
  { id: "book-appointments",   label: "Book appointments",             icon: "🗓" },
  { id: "qualify-prospects",   label: "Qualify prospects",             icon: "🎯" },
  { id: "send-quotes",         label: "Send quotes / pricing",         icon: "💲" },
  { id: "order-status",        label: "Order / delivery status",       icon: "📦" },
  { id: "support-triage",      label: "Triage support tickets",        icon: "🔧" },
  { id: "follow-up",           label: "Follow up with old customers",  icon: "📨" },
];

const CHANNELS = [
  { id: "whatsapp",  label: "WhatsApp"   },
  { id: "telegram",  label: "Telegram"   },
  { id: "email",     label: "Email"      },
  { id: "instagram", label: "Instagram DMs" },
  { id: "webchat",   label: "Website chat" },
  { id: "sms",       label: "SMS"        },
];

const LANGUAGES = [
  "English", "Arabic", "Spanish", "French", "Portuguese", "German",
  "Hindi", "Mandarin", "Turkish", "Russian", "Indonesian",
];

function OnboardingWizard({ open, onClose, onComplete }) {
  const [step, setStep]         = React.useState(0); // 0..6 — 6 = review
  const [answers, setAnswers]   = React.useState({
    website: "", oneLiner: "", customers: "",
    languages: [], useCases: [], channels: [],
    voice: "", voiceNotes: "", avoid: "",
  });
  const [busy, setBusy]         = React.useState(false);
  const [err, setErr]           = React.useState("");
  const [analysis, setAnalysis] = React.useState(null); // { profile, voice, recommendedAgents[] }

  // Website auto-detect state. Mirrors what the Settings → Company
  // "Analyze site" button produces, but runs inside the wizard so the
  // owner doesn't have to fill the rest by hand if their site is
  // readable. Falls back to manual entry if the site is private or the
  // analyser fails.
  const [siteBusy, setSiteBusy]       = React.useState(false);
  const [siteAnalyzed, setSiteAnalyzed] = React.useState(null); // { companyName, summary, location, industry, … }
  const [siteErr, setSiteErr]         = React.useState("");

  React.useEffect(() => {
    if (open) {
      setStep(0); setAnalysis(null); setErr("");
      setSiteAnalyzed(null); setSiteErr(""); setSiteBusy(false);
    }
  }, [open]);

  const analyzeSite = async () => {
    const url = (answers.website || "").trim();
    if (!url) { setSiteErr("Add a URL first."); return; }
    if (!window.citrusAnalyzeWebsite) { setSiteErr("Site analyser not loaded — refresh and try again."); return; }
    setSiteBusy(true); setSiteErr("");
    try {
      const a = await window.citrusAnalyzeWebsite(url);
      if (!a) { setSiteErr("Couldn't read that site. Continue manually below."); setSiteBusy(false); return; }
      setSiteAnalyzed(a);
      // Pre-fill the answers the analyser can confidently derive. The
      // owner reviews / edits each on the corresponding step — we never
      // skip steps, only seed them.
      const next = { ...answers };
      if (a.summary && !answers.oneLiner)   next.oneLiner = a.summary;
      // "Who are your customers" — derive a short hint from products /
      // location / industry. The owner refines on step 2.
      if (!answers.customers) {
        const customerHints = [];
        if (a.industry)            customerHints.push(a.industry.toLowerCase() + " customers");
        if (a.location)            customerHints.push("in " + a.location);
        else if (a.host)           customerHints.push("reached via " + a.host);
        if (customerHints.length)  next.customers = customerHints.join(" ").replace(/^./, (c) => c.toUpperCase()) + ".";
      }
      // Languages: try to surface the page's HTML lang attribute, plus
      // English as a sensible default for B2B sites.
      if ((answers.languages || []).length === 0) {
        const langs = new Set(["English"]);
        const pageLang = (a.title && /[؀-ۿ]/.test(a.title)) ? "Arabic" : null;
        if (pageLang) langs.add(pageLang);
        // Geo heuristic — Egypt / Middle East likely means Arabic too.
        if (a.location && /(egypt|saudi|uae|kuwait|qatar|jordan|lebanon|syria|iraq|bahrain|oman)/i.test(a.location)) {
          langs.add("Arabic");
        }
        next.languages = Array.from(langs);
      }
      setAnswers(next);
    } catch (e) {
      setSiteErr(e.message || "Couldn't read that site.");
    } finally { setSiteBusy(false); }
  };

  if (!open) return null;

  const toggleInList = (key, value) => {
    setAnswers((a) => {
      const cur = new Set(a[key] || []);
      if (cur.has(value)) cur.delete(value); else cur.add(value);
      return { ...a, [key]: Array.from(cur) };
    });
  };

  const next = () => setStep((s) => Math.min(s + 1, 6));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  const submitAnalysis = async (commit) => {
    setBusy(true); setErr("");
    try {
      const r = await fetch(`${SERVER_URL_OB()}/onboarding/intake`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ answers, commit: !!commit }),
      });
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || `${r.status}`);
      setAnalysis(j);
      if (commit) {
        // Refresh the dashboard's view of the profile so the rail picks
        // up the new company name immediately.
        try { window.dispatchEvent(new Event("citrus-brand")); } catch {}
        if (onComplete) onComplete(j);
      } else {
        setStep(6); // go to review
      }
    } catch (e) {
      setErr(e.message || "Couldn't analyse — try again.");
    } finally { setBusy(false); }
  };

  // ---- Step UIs ----
  const Step = ({ n, total, title, sub, children, canNext = true }) => (
    <div className="ob-step">
      <div className="ob-progress">
        {Array.from({ length: total }).map((_, i) => (
          <span key={i} className={`ob-progress-dot ${i <= n ? "is-on" : ""}`} />
        ))}
      </div>
      <h2 className="ob-h">{title}</h2>
      {sub ? <p className="ob-sub">{sub}</p> : null}
      <div className="ob-body">{children}</div>
      <div className="ob-foot">
        {n > 0 ? <button className="btn btn-ghost" onClick={back} disabled={busy}>Back</button> : <span />}
        <div className="ob-foot-actions">
          <button className="btn btn-ghost" onClick={onClose} disabled={busy}>Skip for now</button>
          {n < 5 ? (
            <button className="btn btn-primary" onClick={next} disabled={!canNext || busy}>Continue</button>
          ) : (
            <button className="btn btn-primary" onClick={() => submitAnalysis(false)} disabled={busy}>
              {busy ? "Analysing…" : "See recommendations →"}
            </button>
          )}
        </div>
      </div>
    </div>
  );

  return (
    <div className="ob-backdrop" role="dialog" aria-modal="true">
      <div className="ob-card">
        {step === 0 && (
          <Step n={0} total={6} title="Welcome to Citrus."
            sub="Drop your website and we'll read it. Or skip and answer the questions yourself — takes about a minute either way.">
            <div className="ob-step0-grid">
              <label className="ob-fld">
                <span className="ob-lbl">Your company's website</span>
                <div className="ob-site-row">
                  <input className="ob-input" type="text" placeholder="https://acme.co" value={answers.website}
                    onChange={(e) => { setAnswers({ ...answers, website: e.target.value }); setSiteAnalyzed(null); setSiteErr(""); }}
                    onKeyDown={(e) => { if (e.key === "Enter" && answers.website.trim()) { e.preventDefault(); analyzeSite(); } }}
                    autoFocus />
                  <button className="btn btn-primary ob-site-btn" type="button" onClick={analyzeSite}
                    disabled={siteBusy || !answers.website.trim()}>
                    {siteBusy ? "Reading…" : (siteAnalyzed ? "Re-read" : "Read my site")}
                  </button>
                </div>
                <span className="ob-hint">
                  We'll fetch the page, identify what you do, who you serve, what languages and area you're in, and pre-fill the rest of the wizard. You can edit anything.
                </span>
              </label>

              {siteBusy ? (
                <div className="ob-site-status">
                  <span className="signin-spin ob-site-spin" />
                  Reading your site — this usually takes ~10 seconds.
                </div>
              ) : siteAnalyzed ? (
                <div className="ob-site-result">
                  <div className="ob-site-result-h">
                    <span className="ob-site-check">✓</span>
                    <b>Read your site — drafted the rest of the wizard below.</b>
                  </div>
                  <div className="ob-site-facts">
                    {siteAnalyzed.companyName ? <><span className="ob-site-fact-k">Company</span><b>{siteAnalyzed.companyName}</b></> : null}
                    {siteAnalyzed.industry    ? <><span className="ob-site-fact-k">Industry</span><b>{siteAnalyzed.industry}</b></> : null}
                    {siteAnalyzed.location    ? <><span className="ob-site-fact-k">Area</span><b>{siteAnalyzed.location}</b></> : null}
                    {siteAnalyzed.tz          ? <><span className="ob-site-fact-k">Timezone</span><b>{siteAnalyzed.tz}</b></> : null}
                  </div>
                  {siteAnalyzed.summary ? (
                    <p className="ob-site-summary">"{siteAnalyzed.summary}"</p>
                  ) : null}
                </div>
              ) : null}

              {siteErr ? <p className="ob-err">{siteErr}</p> : null}
            </div>
          </Step>
        )}

        {step === 1 && (
          <Step n={1} total={6} title="What does your business do?"
            sub="One sentence. Skip the marketing fluff — Claude reads this verbatim."
            canNext={!!answers.oneLiner.trim()}>
            <textarea className="ob-input ob-textarea" rows={3}
              placeholder='"We sell engineering and industrial equipment to factories across Egypt."'
              value={answers.oneLiner}
              onChange={(e) => setAnswers({ ...answers, oneLiner: e.target.value })}
              autoFocus />
          </Step>
        )}

        {step === 2 && (
          <Step n={2} total={6} title="Who are your customers?"
            sub="One sentence. Roles, types, geography — whatever's most distinctive.">
            <textarea className="ob-input ob-textarea" rows={3}
              placeholder='"Procurement managers at mid-sized manufacturing plants in Cairo and Alexandria."'
              value={answers.customers}
              onChange={(e) => setAnswers({ ...answers, customers: e.target.value })}
              autoFocus />
          </Step>
        )}

        {step === 3 && (
          <Step n={3} total={6} title="Where do customers reach you?"
            sub="Pick all that apply. Agents will be built around these channels."
            canNext={answers.channels.length > 0}>
            <div className="ob-chips">
              {CHANNELS.map((c) => (
                <button key={c.id} type="button"
                  className={`ob-chip ${answers.channels.includes(c.id) ? "is-on" : ""}`}
                  onClick={() => toggleInList("channels", c.id)}>
                  {c.label}
                </button>
              ))}
            </div>
            <div className="ob-divider" />
            <div className="ob-lbl ob-lbl-spaced">Languages your agents need to speak</div>
            <div className="ob-chips">
              {LANGUAGES.map((l) => (
                <button key={l} type="button"
                  className={`ob-chip ${answers.languages.includes(l) ? "is-on" : ""}`}
                  onClick={() => toggleInList("languages", l)}>
                  {l}
                </button>
              ))}
            </div>
          </Step>
        )}

        {step === 4 && (
          <Step n={4} total={6} title="What's the agent for?"
            sub="Pick everything you'd like an AI agent to handle. We'll recommend specific agents for each."
            canNext={answers.useCases.length > 0}>
            <div className="ob-tiles">
              {USE_CASES.map((u) => (
                <button key={u.id} type="button"
                  className={`ob-tile ${answers.useCases.includes(u.id) ? "is-on" : ""}`}
                  onClick={() => toggleInList("useCases", u.id)}>
                  <span className="ob-tile-icon">{u.icon}</span>
                  <span className="ob-tile-label">{u.label}</span>
                </button>
              ))}
            </div>
          </Step>
        )}

        {step === 5 && (
          <Step n={5} total={6} title="How should they sound?"
            sub="The vibe your agents need to match. You can tweak this any time in Settings."
            canNext={!!answers.voice}>
            <div className="ob-voice-grid">
              {VOICE_OPTIONS.map((v) => (
                <button key={v.id} type="button"
                  className={`ob-voice ${answers.voice === v.id ? "is-on" : ""}`}
                  onClick={() => setAnswers({ ...answers, voice: v.id })}>
                  <span className="ob-voice-label">{v.label}</span>
                  <span className="ob-voice-note">{v.note}</span>
                </button>
              ))}
            </div>
            <label className="ob-fld" style={{ marginTop: 14 }}>
              <span className="ob-lbl">Voice notes (optional)</span>
              <textarea className="ob-input ob-textarea" rows={2}
                placeholder='"Always use Egyptian Arabic when the customer writes in Arabic. Never use ALL CAPS."'
                value={answers.voiceNotes}
                onChange={(e) => setAnswers({ ...answers, voiceNotes: e.target.value })} />
            </label>
            <label className="ob-fld" style={{ marginTop: 14 }}>
              <span className="ob-lbl">Anything agents must NEVER do or say?</span>
              <textarea className="ob-input ob-textarea" rows={2}
                placeholder='"Never quote prices without checking the sheet. Never share competitor info."'
                value={answers.avoid}
                onChange={(e) => setAnswers({ ...answers, avoid: e.target.value })} />
            </label>
            {err ? <p className="ob-err">{err}</p> : null}
          </Step>
        )}

        {step === 6 && analysis && (
          <div className="ob-step">
            <div className="ob-progress">
              {Array.from({ length: 6 }).map((_, i) => <span key={i} className="ob-progress-dot is-on" />)}
            </div>
            <h2 className="ob-h">Here's what we'd build for you.</h2>
            <p className="ob-sub">Based on your answers. Pick which ones to hire — you can always change everything later.</p>

            <div className="ob-recap">
              <div className="ob-recap-row"><span>Company</span><b>{analysis.profile?.name || "—"}</b></div>
              <div className="ob-recap-row"><span>Industry</span><b>{analysis.profile?.industry || "—"}</b></div>
              <div className="ob-recap-row"><span>Voice</span><b>{analysis.voice?.tone || "—"}</b></div>
            </div>

            <div className="ob-agents">
              {(analysis.recommendedAgents || []).map((a, i) => (
                <div key={i} className="ob-agent">
                  <div className="ob-agent-h">
                    <span className="ob-agent-name">{a.name}</span>
                    <span className="ob-agent-role">· {a.role}</span>
                  </div>
                  <p className="ob-agent-brief">{a.brief}</p>
                  <p className="ob-agent-why">Why: {a.why}</p>
                  {Array.isArray(a.channels) && a.channels.length ? (
                    <div className="ob-agent-channels">
                      {a.channels.map((c) => <span key={c} className="ob-chip is-on ob-chip-static">{c}</span>)}
                    </div>
                  ) : null}
                </div>
              ))}
            </div>

            {err ? <p className="ob-err">{err}</p> : null}

            <div className="ob-foot">
              <button className="btn btn-ghost" onClick={() => setStep(5)} disabled={busy}>Back</button>
              <div className="ob-foot-actions">
                <button className="btn btn-ghost" onClick={onClose} disabled={busy}>Close</button>
                <button className="btn btn-primary" onClick={() => submitAnalysis(true)} disabled={busy}>
                  {busy ? "Saving…" : "Save profile + start hiring"}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.OnboardingWizard = OnboardingWizard;
