/* === Cythera form prototype === */

const { useState, useEffect, useMemo, useRef } = React;
const BRAND = window.BRAND || { name: "Cythera", logo: null, emailPh: "avery@company.com.au", phonePh: "+61 4XX XXX XXX" };

// Tweakable defaults persisted by the host
const TWEAK_DEFAULTS = window.BRAND_TWEAKS || { theme: "dark", accent: null };

function ThemeToggle({ theme, setTheme }) {
  return (
    <button
      className="theme-toggle"
      onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
      title="Toggle theme"
    >
      {theme === "dark" ? "◐ Dark" : "◑ Light"}
    </button>
  );
}

function ProgressBar({ stepIndex, totalSteps, onRestart }) {
  // stepIndex 0..totalSteps-1
  return (
    <div className="progress">
      <div className="progress-meta">
        Step {String(stepIndex + 1).padStart(2, "0")} <span style={{ color: "var(--muted-2)" }}>/ {String(totalSteps).padStart(2, "0")}</span>
      </div>
      <div className="progress-bar">
        {Array.from({ length: totalSteps }).map((_, i) => (
          <div
            key={i}
            className={`progress-seg ${i < stepIndex ? "filled" : i === stepIndex ? "partial" : ""}`}
          />
        ))}
      </div>
      {onRestart && <button type="button" className="restart-btn" onClick={onRestart}>↺ Start again</button>}
    </div>
  );
}

function OptionCard({ option, selected, multi, onToggle, idx }) {
  return (
    <button
      type="button"
      className="option"
      aria-pressed={selected}
      data-multi={multi ? "true" : "false"}
      onClick={() => onToggle(option.value)}
    >
      <span className="opt-mark" />
      <span className="opt-label">{option.label}</span>
      {option.desc && <span className="opt-desc">{option.desc}</span>}
      {idx < 9 && <span className="opt-kbd">{idx + 1}</span>}
    </button>
  );
}

function StepView({ step, answer, onChange }) {
  if (step.type === "contact") {
    const c = answer || { name: "", email: "", company: "", phone: "", notes: "" };
    const set = (k, v) => onChange({ ...c, [k]: v });
    return (
      <div className="step-anim">
        <div className="step-header">
          <div className="step-tag"><span className="step-tag-line" />{step.tag}</div>
          <h2 className="step-title">{step.title}</h2>
          <p className="step-sub">{step.sub}</p>
        </div>
        <div className="field-grid">
          <div className="field">
            <label>Full name</label>
            <input type="text" placeholder="Avery Chen" value={c.name} onChange={(e) => set("name", e.target.value)} />
          </div>
          <div className="field">
            <label>Work email</label>
            <input type="email" placeholder={BRAND.emailPh} value={c.email} onChange={(e) => set("email", e.target.value)} />
          </div>
          <div className="field">
            <label>Company</label>
            <input type="text" placeholder="Company name" value={c.company} onChange={(e) => set("company", e.target.value)} />
          </div>
          <div className="field">
            <label>Phone (optional)</label>
            <input type="tel" placeholder={BRAND.phonePh} value={c.phone} onChange={(e) => set("phone", e.target.value)} />
          </div>
          <div className="field full">
            <label>Anything else we should know? (optional)</label>
            <textarea rows={3} placeholder="Context, deadlines, specific concerns…" value={c.notes} onChange={(e) => set("notes", e.target.value)} />
          </div>
        </div>
      </div>
    );
  }

  const isMulti = step.type === "multi";
  const current = isMulti ? (answer || []) : answer;

  const toggle = (value) => {
    if (isMulti) {
      const set = new Set(current || []);
      if (set.has(value)) set.delete(value);
      else set.add(value);
      onChange(Array.from(set));
    } else {
      onChange(value);
    }
  };

  return (
    <div className="step-anim">
      <div className="step-header">
        <div className="step-tag"><span className="step-tag-line" />{step.tag}</div>
        <h2 className="step-title">{step.title}</h2>
        <p className="step-sub">{step.sub}</p>
        {isMulti && <div className="step-hint">Multi-select: pick all that apply</div>}
      </div>
      <div className={`options ${step.options.length > 6 ? "" : ""}`}>
        {step.options.map((opt, i) => (
          <OptionCard
            key={opt.value}
            option={opt}
            selected={isMulti ? current.includes(opt.value) : current === opt.value}
            multi={isMulti}
            onToggle={toggle}
            idx={i}
          />
        ))}
      </div>
    </div>
  );
}

function Preflight({ onStart, onUrgent }) {
  return (
    <div className="preflight step-anim">
      <div className="preflight-eyebrow">
        <span className="status-dot" />{BRAND.name} · Find your pathway
      </div>
      <h1 className="preflight-title">
        Tell us what you're up against.<br />
        We'll point you to the right team.
      </h1>
      <p className="preflight-sub">
        A two-minute guided form. Answer a few questions and you'll get a tailored recommendation, plus a direct line to an advisor. No spam, no automated funnel.
      </p>
      <div className="preflight-actions">
        <button className="preflight-card urgent" onClick={onUrgent}>
          <span className="preflight-icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg>
          </span>
          <span className="preflight-body">
            <strong>Urgent: we may have an active issue</strong>
            <span>Suspicious activity, ransom note, or live incident. Route to Incident Response</span>
          </span>
          <span className="preflight-arrow">→</span>
        </button>
        <button className="preflight-card" onClick={onStart}>
          <span className="preflight-icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9 12l2 2 4-4"/></svg>
          </span>
          <span className="preflight-body">
            <strong>I'm here to plan, scope or improve</strong>
            <span>Walk me through a few questions and recommend the right pathway</span>
          </span>
          <span className="preflight-arrow">→</span>
        </button>
      </div>
      <div className="preflight-foot">
        <span>●</span> Average completion time · 2 min 14 sec
      </div>
    </div>
  );
}

function ResultScreen({ state, onRestart, onEdit }) {
  const pathwayKey = state.urgent ? "incident" : recommendPathway(state);
  const pw = PATHWAYS[pathwayKey];
  const a = state.answers;
  const contact = a.contact || {};
  const inc = a.incident || {};
  const irPhone = BRAND.irPhone || "0800 000 000";
  const tel = "tel:" + irPhone.replace(/[^\d+]/g, "");

  const summaryItems = useMemo(() => {
    const items = [];
    if (state.urgent) {
      if (inc.types && inc.types.length) items.push({ label: "What's happening", value: inc.types.map((v) => IR_TYPES.find((t) => t.value === v)?.label).join(" · ") });
      if (inc.status) items.push({ label: "Still happening", value: IR_STATUS.find((t) => t.value === inc.status)?.label });
      if (contact.notes) items.push({ label: "Details", value: contact.notes });
      return items;
    }
    if (a.concern) items.push({ label: "Primary need", value: readableAnswer("concern", a.concern) });
    if (a.size) items.push({ label: "Team size", value: readableAnswer("size", a.size) });
    if (a.posture) items.push({ label: "Current state", value: readableAnswer("posture", a.posture) });
    if (a.outcomes && a.outcomes.length) {
      items.push({ label: "Desired outcomes", value: readableAnswer("outcomes", a.outcomes).join(" · ") });
    }
    if (a.timeframe) items.push({ label: "Timeframe", value: readableAnswer("timeframe", a.timeframe) });
    return items;
  }, [state]);

  const firstName = (contact.name || "").trim().split(" ")[0] || "there";

  return (
    <div className="result step-anim">
      <div className="result-eyebrow">
        <span className="status-dot" />{state.urgent ? "Request received · Incident response" : "Recommendation ready"}
      </div>

      {state.urgent ? (
        <div className="result-hero">
          <p className="result-hi">Thanks <span className="result-name">{firstName}</span>, your request is with our on-call team.</p>
          <h2 className="result-title">A responder will call you on {contact.phone || "the number you gave us"}.</h2>
          <p className="result-why">Keep your phone close. While you wait, avoid switching off or wiping affected systems where you can, as this can remove evidence we need. Disconnecting them from the network is fine.</p>
          <div className="cta-row">
            <a className="btn btn-critical" href={tel}>Call {irPhone} now <span className="arrow">→</span></a>
            <button className="btn btn-outline" onClick={onEdit}>Edit details</button>
            <div className="cta-meta">On call 24/7</div>
          </div>
        </div>
      ) : (
        <div className="result-hero">
          <p className="result-hi">Thanks <span className="result-name">{firstName}</span>, here's what we'd suggest based on your answers.</p>
          <h2 className="result-title">
            We'd start with<span className="pathway">{pw.code}</span><br />
            {pw.title}
          </h2>
          <p className="result-why">{pw.why}</p>
          <div className="urgency-row">
            <span className="urgency-pill" data-level={pw.urgency.level}>{pw.urgency.label} urgency</span>
            <span className="urgency-text"><strong>{pw.urgency.text}</strong></span>
          </div>
          <div className="cta-row">
            <button className="btn btn-primary" onClick={() => alert(`(Prototype) This would open a calendar booking with a ${BRAND.name} expert.`)}>
              Talk to an expert <span className="arrow">→</span>
            </button>
            <button className="btn btn-outline" onClick={onEdit}>Edit my answers</button>
            <div className="cta-meta">Reply within 1 business day</div>
          </div>
        </div>
      )}

      <div className="summary-grid">
        <div className="summary-card">
          <h3>{state.urgent ? "What you told us" : "Your answers"}</h3>
          <ul className="summary-list">
            {summaryItems.length ? summaryItems.map((item, i) => (
              <li key={i}>
                <span className="sum-label">{item.label}</span>
                <span className="sum-value">{item.value}</span>
              </li>
            )) : <li><span className="sum-label">Details</span><span className="sum-value">-</span></li>}
          </ul>
        </div>
        <div className="summary-card">
          <h3>{state.urgent ? "How we'll reach you" : "Where we'll send it"}</h3>
          <ul className="summary-list">
            <li><span className="sum-label">Name</span><span className="sum-value">{contact.name || "-"}</span></li>
            <li><span className="sum-label">Phone</span><span className="sum-value">{contact.phone || "-"}</span></li>
            <li><span className="sum-label">Email</span><span className="sum-value">{contact.email || "-"}</span></li>
            <li><span className="sum-label">Company</span><span className="sum-value">{contact.company || "-"}</span></li>
          </ul>
        </div>
      </div>

      <div className="result-foot">
        <span></span>
        <button onClick={onRestart}>↺ Start again</button>
      </div>
    </div>
  );
}

function App() {
  const [tweaks, setTweaks] = useTweaks(TWEAK_DEFAULTS);
  const [phase, setPhase] = useState("preflight"); // preflight | form | result
  const [stepIndex, setStepIndex] = useState(0);
  const [answers, setAnswers] = useState({});
  const [urgent, setUrgent] = useState(false);

  // Apply theme to <html>
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme || "dark");
    const r = document.documentElement.style;
    if (tweaks.accent) { r.setProperty("--accent", tweaks.accent); r.setProperty("--accent-2", tweaks.accent); r.setProperty("--accent-soft", `color-mix(in oklab, ${tweaks.accent} 14%, transparent)`); r.setProperty("--accent-2-soft", `color-mix(in oklab, ${tweaks.accent} 14%, transparent)`); }
  }, [tweaks.theme, tweaks.accent]);

  const setTheme = (t) => setTweaks("theme", t);

  // Keyboard shortcuts: 1-9 to pick, Enter to advance, ← to go back
  useEffect(() => {
    if (phase !== "form") return;
    const step = STEPS[stepIndex];
    const onKey = (e) => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
      if (step.type === "contact") return;
      const n = parseInt(e.key, 10);
      if (n >= 1 && n <= 9 && step.options && step.options[n - 1]) {
        const v = step.options[n - 1].value;
        if (step.type === "multi") {
          const cur = new Set(answers[step.id] || []);
          if (cur.has(v)) cur.delete(v); else cur.add(v);
          setAnswers((a) => ({ ...a, [step.id]: Array.from(cur) }));
        } else {
          setAnswers((a) => ({ ...a, [step.id]: v }));
        }
      } else if (e.key === "Enter" && canAdvance()) {
        next();
      } else if (e.key === "ArrowLeft" && stepIndex > 0) {
        back();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [phase, stepIndex, answers]);

  function startForm() {
    setUrgent(false);
    setStepIndex(0);
    setPhase("form");
  }

  function triggerUrgent() {
    setUrgent(true);
    setPhase("incident");
  }

  function submitIncident(d) {
    setAnswers({ incident: { types: d.types, status: d.status }, contact: { name: d.name, phone: d.phone, email: d.email, company: d.company, notes: d.notes }, _ir: d });
    setPhase("result");
  }

  function setAnswer(stepId, value) {
    setAnswers((a) => ({ ...a, [stepId]: value }));
  }

  function canAdvance() {
    const step = STEPS[stepIndex];
    if (!step) return false;
    const v = answers[step.id];
    if (step.type === "single") return !!v;
    if (step.type === "multi") return Array.isArray(v) && v.length > 0;
    if (step.type === "contact") {
      const c = v || {};
      return !!(c.name && c.email && c.company && /@/.test(c.email));
    }
    return false;
  }

  function next() {
    if (!canAdvance()) return;
    if (stepIndex === STEPS.length - 1) {
      setPhase("result");
    } else {
      setStepIndex((i) => i + 1);
    }
  }

  function back() {
    setStepIndex((i) => Math.max(0, i - 1));
  }

  function restart() {
    setPhase("preflight");
    setStepIndex(0);
    setAnswers({});
    setUrgent(false);
  }

  function editAnswers() {
    if (urgent) { setPhase("incident"); return; }
    setPhase("form");
    setStepIndex(0);
  }

  const step = STEPS[stepIndex];

  return (
    <div className="app">
      <header className="topbar">
        <div className="brand">
          {BRAND.logo ? <img src={BRAND.logo} alt={BRAND.name} className="brand-logo" /> : <><span className="brand-mark">C</span><span className="brand-name">CYTHERA</span></>}
          <span className="brand-sep">/</span>
          <span className="brand-product">find your pathway</span>
        </div>
        <div className="topbar-meta" style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span><span className="status-dot" />Secure · Encrypted in transit</span>
          <ThemeToggle theme={tweaks.theme} setTheme={setTheme} />
        </div>
      </header>

      <main className="stage">
        {phase === "preflight" && (
          <Preflight onStart={startForm} onUrgent={triggerUrgent} />
        )}
        {phase === "incident" && (
          <IncidentIntake initial={answers._ir} onBack={restart} onSubmit={submitIncident} />
        )}
        {phase === "form" && (
          <>
            <ProgressBar stepIndex={stepIndex} totalSteps={STEPS.length} onRestart={restart} />
            <div className="card">
              <StepView
                step={step}
                answer={answers[step.id]}
                onChange={(v) => setAnswer(step.id, v)}
              />
              <div className="step-foot">
                <button
                  className="btn btn-ghost"
                  onClick={back}
                  disabled={stepIndex === 0}
                >
                  <span className="arrow">←</span> Back
                </button>
                <button
                  className="btn btn-primary"
                  onClick={next}
                  disabled={!canAdvance()}
                >
                  {stepIndex === STEPS.length - 1 ? "See my recommendation" : "Next"} <span className="arrow">→</span>
                </button>
              </div>
            </div>
          </>
        )}
        {phase === "result" && (
          <ResultScreen
            state={{ answers, urgent }}
            onRestart={restart}
            onEdit={editAnswers}
          />
        )}
      </main>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Appearance" />
        <TweakRadio
          label="Theme"
          value={tweaks.theme}
          onChange={(v) => setTweaks("theme", v)}
          options={[
            { value: "dark", label: "Dark" },
            { value: "light", label: "Light" },
          ]}
        />
        {BRAND.accents && <TweakColor label="Accent" value={tweaks.accent} options={BRAND.accents} onChange={(v) => setTweaks("accent", v)} />}
        <TweakSection label="Demo shortcuts" />
        <TweakButton
          label="Jump to result · MDR sample"
          onClick={() => {
            setAnswers({
              concern: "monitoring",
              size: "201-1000",
              posture: "it_team",
              outcomes: ["detect", "ransomware_ready"],
              timeframe: "quarter",
              contact: { name: "Avery Chen", email: "avery@northwind.com.au", company: "Northwind Logistics", phone: "+61 412 555 901", notes: "" },
            });
            setUrgent(false);
            setPhase("result");
          }}
        />
        <TweakButton
          label="Jump to result · vCISO sample"
          onClick={() => {
            setAnswers({
              concern: "compliance",
              size: "51-200",
              posture: "tools",
              outcomes: ["audit", "board", "roadmap"],
              timeframe: "year",
              contact: { name: "Jordan Patel", email: "jordan@meridian.com.au", company: "Meridian Health", phone: "", notes: "ISO 27001 audit due Q3" },
            });
            setUrgent(false);
            setPhase("result");
          }}
        />
        <TweakButton
          label="Jump to incident form"
          onClick={() => {
            setAnswers({});
            setUrgent(true);
            setPhase("incident");
          }}
        />
        <TweakButton label="Reset to start" secondary onClick={restart} />
      </TweaksPanel>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
