/* global React */
const { useState: useState2 } = React;

const QUESTIONS = [
  {
    id: "financials",
    label: "Financials",
    question: "Can you produce GAAP-compliant financials, with documented revenue recognition policies, reconciled bank statements, and no unresolved intercompany transactions, within 72 hours of a diligence request?",
    options: [
      { v: 3, t: "Yes, we can pull a clean dataroom in under 72 hours" },
      { v: 2, t: "Mostly, minor cleanup needed, but the policies are documented" },
      { v: 1, t: "We have financials, but they'd need a week or more to be diligence-clean" },
      { v: 0, t: "Not yet, this would be a meaningful project" }
    ]
  },
  {
    id: "revrec",
    label: "Revenue Recognition",
    question: "Is your revenue recognition policy written down, consistently applied, and defensible to an investor's accountant?",
    options: [
      { v: 3, t: "Written, applied, reviewed by an outside CPA, defensible under ASC 606 if asked" },
      { v: 2, t: "Written and applied, but not externally validated" },
      { v: 1, t: "We follow a method but haven't formalized it on paper" },
      { v: 0, t: "We recognize revenue when cash hits, or we're not sure" },
      { v: 2, t: "Pre-revenue, not applicable yet" }
    ]
  },
  {
    id: "captable",
    label: "Cap Table",
    question: "Where does your cap table live, and how confident are you in it?",
    options: [
      { v: 3, t: "On Carta (or similar), fully tracked, every SAFE and option grant accounted for" },
      { v: 2, t: "On a spreadsheet (Excel, Google Sheets) we maintain ourselves; it's accurate but not professionally managed" },
      { v: 1, t: "Our lawyer maintains it; I couldn't walk through it without them" },
      { v: 0, t: "We have something written down, but I'd be uncomfortable showing it to an investor" }
    ]
  },
  {
    id: "cac",
    label: "Customer Acquisition",
    question: "How do new clients actually find you and decide to work with you today?",
    options: [
      { v: 3, t: "We have a documented sales process with predictable conversion at each stage, referrals, outbound, content, all tracked" },
      { v: 2, t: "One source is reliable (e.g. referrals, or a specific outbound motion), the rest are opportunistic" },
      { v: 1, t: "Mostly word-of-mouth and the founder's network, but it's been working" },
      { v: 0, t: "Pre-revenue, pre-customer, or running pilots that haven't converted to paid yet" }
    ]
  },
  {
    id: "ip",
    label: "IP Ownership",
    question: "Does your company own all IP core to the product? (Not you personally, not a co-founder, not a former contractor.)",
    options: [
      { v: 3, t: "Yes. Every contributor, employees and contractors, signed IP assignments and we have the executed documents on file." },
      { v: 2, t: "Employees are covered. Contractor coverage is incomplete or inconsistent." },
      { v: 1, t: "Probably, but I haven't audited the paperwork." },
      { v: 0, t: "There are unresolved IP or ownership questions." }
    ]
  },
  {
    id: "governance",
    label: "Governance",
    question: "Are your board minutes, written consents, and corporate records current and organized, and do you have a clean compliance file (Delaware franchise tax, foreign qualifications, EIN, etc.)?",
    options: [
      { v: 3, t: "Yes, board book is current and a dataroom exists" },
      { v: 2, t: "Mostly, some catch-up needed but no skeletons" },
      { v: 1, t: "Records exist somewhere; nothing is organized" },
      { v: 0, t: "This is a known gap" }
    ]
  },
  {
    id: "narrative",
    label: "Investor Narrative",
    question: "Can you articulate, in writing, why your business is venture-scale, what specifically de-risks it now, and what the next round will fund?",
    options: [
      { v: 3, t: "Yes, three paragraphs, written down, tested with investors" },
      { v: 2, t: "I can say it, but it's not formalized in a memo" },
      { v: 1, t: "I have a deck but no written narrative behind it" },
      { v: 0, t: "I'd want help thinking this through" }
    ]
  }
];

const SCORE_BANDS = [
  { min: 18, max: 21, label: "Diligence-ready", tone: "var(--accent)", verdict: "You're operationally ready to enter a Tier-1 process. The question now is investor selection and narrative, not preparation.", recommendation: "The Pitch Narrative Audit will sharpen your story for the rooms you're walking into. If you'd rather have a senior operator alongside you through the raise, inquire about a retainer.", primaryLabel: "Pitch Narrative Audit · $3,750", primaryHref: "#engagements", secondaryLabel: "Inquire about a retainer", secondaryHref: "#apply" },
  { min: 12, max: 17, label: "Close, with focused work", tone: "var(--teal)", verdict: "You're directionally ready, with two to four specific gaps that institutional diligence will surface in week one. Most are fixable in 30 to 45 days.", recommendation: "The Initial Exposure Assessment will rank exactly what to fix and in what order. If your gaps are bigger than punch-list-sized, inquire about a retainer.", primaryLabel: "Initial Exposure Assessment · $1,950", primaryHref: "#engagements", secondaryLabel: "Inquire about a retainer", secondaryHref: "#apply" },
  { min: 6, max: 11, label: "Pre-diligence", tone: "var(--accent-deep)", verdict: "You have real momentum but the operational scaffolding hasn't caught up. Going to market now risks a delayed or repriced round.", recommendation: "Start with the Exposure Assessment to map the gaps, or inquire about a retainer if you'd rather have someone in the work with you.", primaryLabel: "Initial Exposure Assessment · $1,950", primaryHref: "#engagements", secondaryLabel: "Inquire about a retainer", secondaryHref: "#apply" },
  { min: 0, max: 5, label: "Foundational", tone: "var(--ink-deepest)", verdict: "The operational risk of a raise right now is high. Most founders in this band fix the foundation in one quarter and raise stronger for it.", recommendation: "Start with the Exposure Assessment to see what's between you and ready, or inquire about a Fractional COO engagement to do the work alongside you.", primaryLabel: "Initial Exposure Assessment · $1,950", primaryHref: "#engagements", secondaryLabel: "Inquire about Fractional COO", secondaryHref: "#apply" }
];

const Diagnostic = () => {
  const [step, setStep] = useState2(0); // 0 intro, 1..7 questions, 8 email gate, 9 result
  const [answers, setAnswers] = useState2({});
  const [email, setEmail] = useState2("");
  const [name, setName] = useState2("");
  const [company, setCompany] = useState2("");

  const total = QUESTIONS.length;
  const score = Object.values(answers).reduce((a, b) => a + b, 0);
  const band = SCORE_BANDS.find(b => score >= b.min && score <= b.max) || SCORE_BANDS[3];

  const select = (id, v) => {
    const next = { ...answers, [id]: v };
    setAnswers(next);
    if (step <= total) setTimeout(() => setStep(step + 1), 200);
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!email || !email.includes("@")) return;
    try {
      await fetch("https://api.brevo.com/v3/contacts", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "api-key": "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"
        },
        body: JSON.stringify({
          email: email,
          attributes: {
            FIRSTNAME: name,
            COMPANY: company,
            DIAGNOSTIC_SCORE: score,
            DIAGNOSTIC_BAND: band.label
          },
          listIds: [4],
          updateEnabled: true
        })
      });
    } catch (err) {
      console.error("Brevo error:", err);
    }
    setStep(total + 2);
  };

  return (
    <section id="diagnostic" className="dark" data-result-step={step === total + 2 ? "true" : "false"}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "minmax(260px, 1fr) 2fr", gap: 64 }} className="diag-grid">
          {/* LEFT, context */}
          <div>
            <div className="eyebrow-light" style={{ marginBottom: 24 }}>The 7-Question Diagnostic</div>
            <h2 style={{ color: "#fff" }}>Score your raise against the questions Tier-1 investors actually ask.</h2>
            <p style={{ color: "rgba(255,255,255,0.72)", fontSize: 17, marginTop: 24 }}>
              Seven questions. Three minutes. No email until you see your score. We send the full report, with sourced citations and a prioritized punch-list, afterward.
            </p>
            <div style={{ marginTop: 40, paddingTop: 28, borderTop: "1px solid rgba(255,255,255,0.12)", fontFamily: "var(--sans)", fontSize: 13, color: "rgba(255,255,255,0.5)" }}>
              <div style={{ marginBottom: 10, letterSpacing: "0.12em", textTransform: "uppercase", fontSize: 11 }}>Sourced from</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }}>
                <li>PwC Deals Practice, 2024</li>
                <li>SEC Division of Corporation Finance</li>
                <li>Sequoia internal diligence framework</li>
                <li>NVCA Model Documents</li>
              </ul>
            </div>
          </div>

          {/* RIGHT, interactive */}
          <div style={{ background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)", padding: "clamp(24px, 4vw, 48px)" }}>
            {/* Progress */}
            {step > 0 && step <= total && (
              <div style={{ marginBottom: 32 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(255,255,255,0.55)", marginBottom: 10 }}>
                  <span>Question {step} of {total}</span>
                  <span>{QUESTIONS[step - 1].label}</span>
                </div>
                <div style={{ height: 2, background: "rgba(255,255,255,0.1)" }}>
                  <div style={{ height: 2, background: "var(--accent)", width: `${(step / total) * 100}%`, transition: "width .3s ease" }} />
                </div>
              </div>
            )}

            {/* Intro */}
            {step === 0 && (
              <div>
                <div style={{ fontFamily: "var(--display)", fontSize: 60, color: "var(--accent)", lineHeight: 1, marginBottom: 8 }}>7</div>
                <h3 style={{ color: "#fff", marginBottom: 16 }}>Questions every Tier-1 investor will ask.</h3>
                <p style={{ color: "rgba(255,255,255,0.72)" }}>
                  Before a term sheet. Before a partner meeting. Before the associate gets on a call. These are the questions that decide whether your raise moves forward, or stalls in the first week of diligence.
                </p>
                <button className="btn btn-accent" style={{ marginTop: 24 }} onClick={() => setStep(1)}>
                  Begin diagnostic <span aria-hidden="true">→</span>
                </button>
              </div>
            )}

            {/* Questions */}
            {step > 0 && step <= total && (
              <div>
                <h3 style={{ color: "#fff", fontSize: 22, lineHeight: 1.35, marginBottom: 28, fontFamily: "var(--serif)", fontWeight: 500 }}>
                  {QUESTIONS[step - 1].question}
                </h3>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {QUESTIONS[step - 1].options.map((o, i) => {
                    const active = answers[QUESTIONS[step - 1].id] === o.v;
                    return (
                      <button
                        key={i}
                        onClick={() => select(QUESTIONS[step - 1].id, o.v)}
                        style={{
                          textAlign: "left",
                          padding: "16px 20px",
                          background: active ? "rgba(21,90,193,0.2)" : "rgba(255,255,255,0.03)",
                          border: `1px solid ${active ? "var(--accent)" : "rgba(255,255,255,0.12)"}`,
                          color: "#fff",
                          fontFamily: "var(--sans)",
                          fontSize: 15,
                          cursor: "pointer",
                          transition: "all .15s",
                          display: "flex", gap: 14, alignItems: "flex-start"
                        }}
                        onMouseEnter={e => { if (!active) e.currentTarget.style.background = "rgba(255,255,255,0.06)"; }}
                        onMouseLeave={e => { if (!active) e.currentTarget.style.background = "rgba(255,255,255,0.03)"; }}
                      >
                        <span style={{ fontFamily: "var(--display)", fontSize: 12, color: "var(--accent)", letterSpacing: "0.1em", marginTop: 3, minWidth: 18 }}>{String.fromCharCode(65 + i)}</span>
                        <span>{o.t}</span>
                      </button>
                    );
                  })}
                </div>
                {step > 1 && (
                  <button onClick={() => setStep(step - 1)} style={{ marginTop: 20, background: "none", border: "none", color: "rgba(255,255,255,0.55)", fontFamily: "var(--sans)", fontSize: 13, cursor: "pointer" }}>← Back</button>
                )}
              </div>
            )}

            {/* Email gate */}
            {step === total + 1 && (
              <form onSubmit={submit}>
                <div className="eyebrow-light" style={{ marginBottom: 14 }}>Diagnostic complete</div>
                <h3 style={{ color: "#fff", marginBottom: 16 }}>Your score is ready.</h3>
                <p style={{ color: "rgba(255,255,255,0.72)", marginBottom: 24 }}>
                  Where should we send your full readiness report, with the score, the gaps, and a prioritized 30-day punch-list?
                </p>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  <input required value={name} onChange={e => setName(e.target.value)} placeholder="Your name" style={inputStyle} />
                  <input required value={company} onChange={e => setCompany(e.target.value)} placeholder="Company" style={inputStyle} />
                  <input required type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" style={inputStyle} />
                </div>
                <button type="submit" className="btn btn-accent" style={{ marginTop: 20, width: "100%", justifyContent: "center" }}>
                  Show my score & send the report <span aria-hidden="true">→</span>
                </button>
                <p style={{ fontSize: 12, color: "rgba(255,255,255,0.4)", fontFamily: "var(--sans)", marginTop: 14, marginBottom: 0 }}>
                  We don't sell, share, or rent your information. Period.
                </p>
              </form>
            )}

            {/* Result */}
            {step === total + 2 && (
              <div className="diag-result-light">
                <div style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink-muted)", marginBottom: 14 }}>Your score</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 16, marginBottom: 20 }}>
                  <div style={{ fontFamily: "var(--display)", fontSize: 84, color: band.tone, lineHeight: 1 }}>{score}</div>
                  <div style={{ fontFamily: "var(--sans)", fontSize: 14, color: "var(--ink-muted)" }}>/ 21</div>
                </div>
                <div style={{ fontFamily: "var(--sans)", fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase", color: band.tone, marginBottom: 8 }}>{band.label}</div>
                <p style={{ color: "var(--ink)", fontSize: 18, lineHeight: 1.5 }}>{band.verdict}</p>
                <div style={{ marginTop: 28, padding: 24, background: "var(--bg-warm)", border: "1px solid var(--line)" }}>
                  <div style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink-muted)", marginBottom: 8 }}>Recommended next step</div>
                  <p style={{ color: "var(--ink)", margin: 0, fontSize: 16, lineHeight: 1.55 }}>{band.recommendation}</p>
                </div>
                {band.primaryLabel && band.primaryLabel.includes("Exposure") && (
                  <div style={{ marginTop: 20, padding: 20, border: "1px solid var(--line)", background: "#fff" }}>
                    <div style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink-muted)", marginBottom: 10 }}>What the Exposure Assessment is</div>
                    <p style={{ color: "var(--ink)", margin: 0, fontSize: 15, lineHeight: 1.6 }}>
                      A two-week, written diligence-readiness evaluation. We collect a structured questionnaire, review your cap table, financials, narrative, and operating cadence, then send back a ranked remediation list: every gap an institutional associate will surface, prioritized by what to fix first and what's safe to defer. It maps directly to the dimensions your diagnostic flagged, so you spend the next 30 to 60 days fixing the right things in the right order.
                    </p>
                  </div>
                )}
                <div className="row" style={{ marginTop: 24, gap: 12, flexWrap: "wrap" }}>
                  <a href={band.primaryHref} className="btn btn-primary">{band.primaryLabel}</a>
                  <a href={band.secondaryHref} className="btn btn-ghost">{band.secondaryLabel}</a>
                </div>
                <p style={{ marginTop: 18, fontFamily: "var(--sans)", fontSize: 13, color: "var(--ink-muted)" }}>
                  Want something else? <a href="#engagements" style={{ color: "var(--ink)", textDecoration: "underline" }}>See all services</a> · <a href="mailto:info@avisenstrategies.com?subject=Question%20about%20Avisen%20services" style={{ color: "var(--ink)", textDecoration: "underline" }}>Still have questions?</a>
                </p>
                <p style={{ fontSize: 12, color: "var(--ink-muted)", fontFamily: "var(--sans)", marginTop: 24 }}>
                  Full report sent to {email || "your inbox"} in the next 5 minutes.
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .diag-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
        section#diagnostic[data-result-step="true"] { background: var(--bg); color: var(--ink); }
        section#diagnostic[data-result-step="true"] h2,
        section#diagnostic[data-result-step="true"] h3 { color: var(--ink); }
        section#diagnostic[data-result-step="true"] .diag-intro-wrap { display: none; }
      `}</style>
    </section>
  );
};

const inputStyle = {
  background: "rgba(255,255,255,0.03)",
  border: "1px solid rgba(255,255,255,0.16)",
  color: "#fff",
  fontFamily: "var(--sans)",
  fontSize: 15,
  padding: "14px 16px",
  outline: "none",
  width: "100%"
};

Object.assign(window, { Diagnostic });
