// Use cases + AI onboarding — translating "build anything" into buyer language
const { useState: useStateU, useEffect: useEffectU, useRef: useRefU } = React;

/* =============================================================================
   USE CASES — buyers don't search for "low-code platform", they search for
   the specific thing that's broken. Lead with their words.
   ============================================================================= */

const USE_CASES = [
  {
    id: "spreadsheet",
    said: "Replace our spreadsheet-based approval process.",
    tag: "Operations",
    pain: "A shared workbook nobody trusts, an approval chain that lives in email, and no way to prove who signed off what.",
    build: "A multi-stage approval workflow with electronic authorisation, conditional routing and a full audit trail. Approvers act from an email link; the record updates itself.",
    parts: ["Workflows", "Electronic authorisation", "Auditing", "E-mail templates"],
    proof: ["Every decision timestamped and attributable", "Rollback to any previous version", "No more 'which copy is current?'"],
    weeks: "2–4",
  },
  {
    id: "portal",
    said: "Launch a secure customer portal.",
    tag: "Customer-facing",
    pain: "Customers phone and email for information you already hold. Staff re-key it. Nobody has a self-service option.",
    build: "A branded portal where customers log in to see only their own records — documents, orders, cases, invoices — with row-level permissions enforced by the platform, not by hope.",
    parts: ["Security groups", "Row-level permissions", "2FA", "Document management"],
    proof: ["Default-deny access model", "SSO or platform accounts", "Custom domain and theme"],
    weeks: "3–6",
  },
  {
    id: "access",
    said: "Modernise our Access database.",
    tag: "Migration",
    pain: "A business-critical Access or Excel system built by someone who left. It only runs on one machine, has no backups, and breaks when Windows updates.",
    build: "Drop the spreadsheet in and easy-create mode detects field types and builds a proper datastore. You get web access, real permissions, backups, audit and an API — same data, no rewrite.",
    parts: ["Easy-create mode", "Data Import System", "Datastores", "Deployments"],
    proof: ["5 import methods incl. update-existing", "Multi-user from day one", "Accessible anywhere, backed up nightly"],
    weeks: "1–3",
  },
  {
    id: "supplier",
    said: "Build a supplier onboarding system.",
    tag: "Procurement",
    pain: "Onboarding runs on PDFs and chasing. Compliance documents expire without anyone noticing.",
    build: "A self-service onboarding flow with staged forms, document upload with expiry tracking, automated chase emails and an approval dashboard for your team.",
    parts: ["Multi-stage forms", "File uploads", "Automated tasks", "Reports"],
    proof: ["Suppliers complete their own data", "Expiry reminders sent automatically", "Approve or reject with reasons logged"],
    weeks: "3–5",
  },
  {
    id: "booking",
    said: "Create a regulated booking and reporting platform.",
    tag: "Regulated",
    pain: "Bookings across multiple sites, capacity rules, attendance evidence — and an auditor who wants a report you can't produce.",
    build: "Unlimited calendars with per-location availability, slot or range booking, attendance recording, automated confirmations, and a report builder that auto-joins the underlying tables.",
    parts: ["Booking calendars", "Attendance recording", "Reports", "Auditing"],
    proof: ["Recurring availability with overrides", "E-mail and SMS confirmations", "Evidence trail for inspection"],
    weeks: "4–8",
  },
  {
    id: "casework",
    said: "Track cases from referral to outcome.",
    tag: "Casework",
    pain: "Cases tracked across a mailbox, a spreadsheet and someone's memory. Reporting to funders takes days.",
    build: "A case management system with stages, assignment, SLA timers, document attachment and outcome recording — plus scheduled reports that email themselves to stakeholders.",
    parts: ["Datastores", "Workflows", "Scheduled tasks", "Summary reports"],
    proof: ["Full history per case", "Caseload dashboards per worker", "Funder reports generated, not assembled"],
    weeks: "3–6",
  },
  {
    id: "saas",
    said: "Turn our service into a SaaS product.",
    tag: "Commercial",
    pain: "You have a process clients pay for, but no product to sell them — and building tenancy and billing from scratch is a year of work.",
    build: "Hard-isolated tenants with per-tenant configuration, a subscription engine with tiers and free trials, and Stripe recurring billing that pauses access on failed payment.",
    parts: ["Multitenancy", "Subscription engine", "Stripe", "Admin panel"],
    proof: ["Tenants manage their own users", "Tiered feature access", "Onboarding and billing included"],
    weeks: "6–10",
  },
  {
    id: "integrate",
    said: "Get our systems talking to each other.",
    tag: "Integration",
    pain: "Finance, operations and the website all hold a version of the truth. Someone re-keys between them every week.",
    build: "Link external databases directly, sync datastores between instances, and expose a permission-aware REST API — with custom functions where an off-the-shelf connector won't do.",
    parts: ["API engine", "External databases", "Datastore sync", "Custom functions"],
    proof: ["Same permission rules as the UI", "Token-based clients with call logging", "No more re-keying"],
    weeks: "2–5",
  },
];

// Track a media query (default: the ≤900px "mobile" breakpoint used for the
// use-cases layout). Initialised synchronously so the very first render already
// picks the right layout — no flash of the wrong variant.
function useMediaQueryU(query) {
  const [matches, setMatches] = useStateU(
    () => (typeof window !== "undefined" && window.matchMedia)
      ? window.matchMedia(query).matches
      : false
  );
  useEffectU(() => {
    if (typeof window === "undefined" || !window.matchMedia) return;
    const mq = window.matchMedia(query);
    const sync = () => setMatches(mq.matches);
    sync();
    // Primary: the media-query change event (efficient, fires on breakpoint cross).
    if (mq.addEventListener) mq.addEventListener("change", sync);
    else mq.addListener(sync); // Safari < 14
    // Fallback: some environments don't dispatch MQL change on resize — re-check
    // on window resize too. setState bails out when the value is unchanged, so
    // this stays cheap.
    window.addEventListener("resize", sync);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener("change", sync);
      else mq.removeListener(sync);
      window.removeEventListener("resize", sync);
    };
  }, [query]);
  return matches;
}

// Shared detail body for a use case. `compact` drops the tag pill + repeated
// quote heading (the accordion trigger already shows those), keeping the panel
// tight when it expands inline on mobile.
function UseCaseDetail({ uc, onNavigate, compact }) {
  return (
    <div className="uc-detail">
      {!compact && (
        <React.Fragment>
          <div className="uc-detail-head">
            <span className="uc-tag solid">{uc.tag}</span>
            <span className="uc-weeks">{uc.weeks} weeks typical</span>
          </div>
          <blockquote className="uc-said">{uc.said}</blockquote>
        </React.Fragment>
      )}

      <div className="uc-block">
        <h4>What's actually going wrong</h4>
        <p>{uc.pain}</p>
      </div>
      <div className="uc-block">
        <h4>What we build</h4>
        <p>{uc.build}</p>
      </div>

      <ul className="uc-proof">
        {uc.proof.map(p => (
          <li key={p}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 13l4 4L19 7"/></svg>
            {p}
          </li>
        ))}
      </ul>

      <div className="uc-parts">
        <span className="uc-parts-label">Built from</span>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {uc.parts.map(p => <span key={p} className="uc-part">{p}</span>)}
        </div>
      </div>

      <button className="btn btn-primary" style={{ marginTop: 24, alignSelf: "flex-start" }} onClick={() => onNavigate && onNavigate("contact")}>
        Talk about this one
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
      </button>
    </div>
  );
}

function UseCasesSection({ onNavigate }) {
  const [active, setActive] = useStateU(0);
  const isMobile = useMediaQueryU("(max-width: 900px)");
  const uc = USE_CASES[active] || USE_CASES[0];

  return (
    <section className="usecases">
      <div className="container">
        <div style={{ maxWidth: 820, marginBottom: 48 }}>
          <span className="eyebrow">Where it fits</span>
          <h2 className="h-large" style={{ marginTop: 16 }}>
            You're not shopping for a platform.<br/>
            <em style={{ fontFamily: "Instrument Serif, serif", fontStyle: "italic", fontWeight: 400 }} className="grad-text">You're trying to fix something.</em>
          </h2>
          <p className="lead" style={{ marginTop: 16 }}>
            "Build almost any application" is true, and useless. Here's what people actually ask us for — pick the one that sounds like your week.
          </p>
        </div>

        {isMobile ? (
          /* Mobile: an accordion so every scenario title is visible at once —
             tap one to expand its detail inline (no horizontal swiping). */
          <div className="uc-accordion">
            {USE_CASES.map((u, i) => {
              const open = active === i;
              return (
                <div className={"uc-acc-item" + (open ? " is-open" : "")} key={u.id}>
                  <button
                    type="button"
                    className="uc-acc-trigger"
                    aria-expanded={open}
                    onClick={() => setActive(open ? -1 : i)}
                  >
                    <span className="uc-acc-main">
                      <span className="uc-quote">{u.said}</span>
                      <span className="uc-acc-meta">
                        <span className="uc-tag">{u.tag}</span>
                        <span className="uc-acc-weeks">{u.weeks} wks</span>
                      </span>
                    </span>
                    <svg className="uc-acc-chevron" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg>
                  </button>
                  {open && <UseCaseDetail uc={u} onNavigate={onNavigate} compact />}
                </div>
              );
            })}
          </div>
        ) : (
          <div className="uc-grid">
            <div className="uc-list" role="tablist" aria-label="Use cases">
              {USE_CASES.map((u, i) => (
                <button
                  key={u.id}
                  role="tab"
                  aria-selected={active === i}
                  className={"uc-item" + (active === i ? " is-active" : "")}
                  onClick={() => setActive(i)}
                >
                  <span className="uc-quote">{u.said}</span>
                  <span className="uc-tag">{u.tag}</span>
                </button>
              ))}
            </div>

            <UseCaseDetail key={uc.id} uc={uc} onNavigate={onNavigate} />
          </div>
        )}
      </div>
    </section>
  );
}

/* =============================================================================
   AI ONBOARDING — answer a few questions, the platform builds v1
   ============================================================================= */

const AI_SCRIPT = [
  { q: "What do you want to build?", a: "A supplier onboarding system for our procurement team.", think: "Understanding the domain" },
  { q: "Who will use it?", a: "Around 200 suppliers self-serving, plus 12 internal reviewers.", think: "Sizing users and roles" },
  { q: "What information do you need to collect?", a: "Company details, insurance certificates, bank details and H&S policies.", think: "Deriving your data model" },
  { q: "Does anything need approving?", a: "Yes — a reviewer signs off before a supplier goes active.", think: "Designing the workflow" },
  { q: "Anything that expires?", a: "Insurance and H&S documents, annually.", think: "Adding expiry tracking" },
];

const AI_OUTPUT = [
  { icon: "▦", name: "4 datastores", detail: "Supplier, Document, Review, Category — with relationships" },
  { icon: "▤", name: "3-stage onboarding form", detail: "Conditional fields, file upload, save-and-resume" },
  { icon: "◉", name: "3 security groups", detail: "Supplier · Reviewer · Procurement Admin, row-level scoped" },
  { icon: "⇄", name: "Approval workflow", detail: "Electronic authorisation with reject-and-return" },
  { icon: "↻", name: "2 scheduled tasks", detail: "Expiry chase at 60 and 30 days" },
  { icon: "▥", name: "Reviewer dashboard", detail: "Pending queue, ageing chart, exception list" },
];

function AiOnboardingSection() {
  const [step, setStep] = useStateU(-1);      // -1 idle, 0..n-1 questions, n thinking, n+1 done
  const [typed, setTyped] = useStateU("");
  const ref = useRefU(null);
  const started = useRefU(false);

  const total = AI_SCRIPT.length;
  const phase = step < 0 ? "idle" : step < total ? "asking" : step === total ? "building" : "done";

  // Auto-start when scrolled into view
  useEffectU(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started.current) {
        started.current = true;
        setStep(0);
      }
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Type out the current answer, then advance
  useEffectU(() => {
    if (phase !== "asking") return;
    const answer = AI_SCRIPT[step].a;
    setTyped("");
    let i = 0;
    const typer = setInterval(() => {
      i += 2;
      setTyped(answer.slice(0, i));
      if (i >= answer.length) {
        clearInterval(typer);
        setTimeout(() => setStep(s => s + 1), 850);
      }
    }, 22);
    return () => clearInterval(typer);
  }, [step, phase]);

  // Building pause
  useEffectU(() => {
    if (phase !== "building") return;
    const t = setTimeout(() => setStep(s => s + 1), 2200);
    return () => clearTimeout(t);
  }, [phase]);

  const replay = () => { setStep(0); setTyped(""); };

  return (
    <section className="ai-onb" ref={ref}>
      <div className="container">
        <div className="ai-head">
          <div>
            <span className="eyebrow" style={{ color: "rgba(255,255,255,0.55)" }}>New · AI onboarding</span>
            <h2 className="h-large" style={{ marginTop: 16, color: "#fff" }}>
              Answer five questions.<br/>
              <em style={{ fontFamily: "Instrument Serif, serif", fontStyle: "italic", fontWeight: 400 }} className="grad-text">Get version one.</em>
            </h2>
          </div>
          <p style={{ color: "rgba(230,236,255,0.62)", fontSize: 16, lineHeight: 1.6, maxWidth: 400, textWrap: "pretty" }}>
            Describing what you need is the hard part. Our AI onboarding asks about your process in plain English, then builds the datastores, forms, permissions and workflow for you — a working first version you can open, use and change.
          </p>
        </div>

        <div className="ai-stage">
          {/* Conversation */}
          <div className="ai-chat">
            <div className="ai-chat-bar">
              <span className="ai-dot"></span>
              <span>Onboarding assistant</span>
              {phase !== "idle" && (
                <button className="ai-replay" onClick={replay}>Replay</button>
              )}
            </div>
            <div className="ai-chat-body">
              {AI_SCRIPT.map((s, i) => {
                if (step < i) return null;
                const answered = step > i;
                return (
                  <div key={i} className="ai-turn">
                    <div className="ai-msg ai-q">{s.q}</div>
                    <div className="ai-msg ai-a">
                      {answered ? s.a : typed}
                      {!answered && <span className="ai-caret"></span>}
                    </div>
                  </div>
                );
              })}
              {phase === "building" && (
                <div className="ai-thinking">
                  <span className="ai-spin"></span>
                  <span>Designing your application…</span>
                </div>
              )}
              {phase === "done" && (
                <div className="ai-done-note">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 13l4 4L19 7"/></svg>
                  Version one is ready — open it and start editing.
                </div>
              )}
            </div>
          </div>

          {/* Output */}
          <div className="ai-out">
            <div className="ai-out-head">
              <span>What it built</span>
              {phase === "done" && <span className="ai-out-badge">Ready</span>}
            </div>
            {phase !== "done" ? (
              <div className="ai-out-waiting">
                {AI_OUTPUT.map((o, i) => (
                  <div key={o.name} className="ai-out-ghost" style={{ animationDelay: `${i * 120}ms` }}></div>
                ))}
                <p>{phase === "building" ? "Assembling your application…" : "Answer the questions to see the output."}</p>
              </div>
            ) : (
              <div className="ai-out-list">
                {AI_OUTPUT.map((o, i) => (
                  <div key={o.name} className="ai-out-item sim-pop" style={{ animationDelay: `${i * 110}ms` }}>
                    <span className="ai-out-icon">{o.icon}</span>
                    <div>
                      <strong>{o.name}</strong>
                      <span>{o.detail}</span>
                    </div>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" className="ai-out-tick"><path d="M5 13l4 4L19 7"/></svg>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        <p className="ai-foot">
          The AI writes the first draft — not the last word. Everything it produces is ordinary platform configuration you can open in the visual builder and change, exactly as if you'd built it by hand.
        </p>
      </div>
    </section>
  );
}

Object.assign(window, { UseCasesSection, AiOnboardingSection, USE_CASES });
