/* global React, Icon */

function demoWowModeById(id) {
  const data = window.DEMO_WOW_DATA || { modes: [] };
  return data.modes.find((m) => m.id === id) || data.modes[0];
}

function DemoWowPage() {
  const data = window.DEMO_WOW_DATA || { modes: [], loadingLines: [], sensitiveFields: [] };
  const [previewModeId, setPreviewModeId] = React.useState("deal");
  const [selectedId, setSelectedId] = React.useState(null);
  const [step, setStep] = React.useState("select");
  const [inputValue, setInputValue] = React.useState("");
  const [usedSample, setUsedSample] = React.useState(false);
  const [sourceType, setSourceType] = React.useState("doc");
  const [selectedDeals, setSelectedDeals] = React.useState(() =>
    (data.sourceDeals || []).filter((d) => d.selected).slice(0, 4).map((d) => d.id)
  );
  const [loadingIndex, setLoadingIndex] = React.useState(0);
  const selectedMode = selectedId ? demoWowModeById(selectedId) : null;

  React.useEffect(() => {
    if (step !== "loading") return undefined;
    setLoadingIndex(0);
    const lineTimer = window.setInterval(() => {
      setLoadingIndex((i) => Math.min(i + 1, data.loadingLines.length - 1));
    }, 520);
    const resultTimer = window.setTimeout(() => {
      window.clearInterval(lineTimer);
      setStep("result");
    }, 1900);
    return () => {
      window.clearInterval(lineTimer);
      window.clearTimeout(resultTimer);
    };
  }, [step, data.loadingLines.length]);

  const chooseMode = (id) => {
    setSelectedId(id);
    setInputValue("");
    setUsedSample(false);
    setSourceType(id === "meeting" ? "doc" : "crm");
    setStep("source");
    window.history.replaceState(null, "", "#/demo-wow");
    window.setTimeout(() => document.querySelector(".demo-wow-flow")?.scrollIntoView({ behavior: "smooth", block: "start" }), 80);
  };

  const useSample = (id = selectedId || "deal") => {
    const mode = demoWowModeById(id);
    setSelectedId(id);
    setInputValue(mode.sample || "");
    setUsedSample(true);
    setStep("anonymize");
    window.history.replaceState(null, "", "#/demo-wow");
    window.setTimeout(() => document.querySelector(".demo-wow-flow")?.scrollIntoView({ behavior: "smooth", block: "start" }), 80);
  };

  const startFromHero = () => {
    chooseMode(previewModeId);
  };

  const canAnalyze = inputValue.trim().length > 0;
  const selectedSourceDeals = (data.sourceDeals || []).filter((d) => selectedDeals.includes(d.id));
  const toggleSourceDeal = (id) => {
    setSelectedDeals((current) => {
      if (current.includes(id)) return current.filter((dealId) => dealId !== id);
      if (current.length >= 5) return current;
      return [...current, id];
    });
  };
  const continueFromSource = () => {
    if (sourceType === "crm") {
      const mode = selectedMode || demoWowModeById(selectedId);
      const dealLines = selectedSourceDeals.length
        ? selectedSourceDeals.map((d) => `${d.company} — ${d.stage} — ${d.amount} — ${d.signal}`).join("\n")
        : "ProspectCo — Proposal — €48k — No buyer-owned next step";
      setInputValue(`${mode.title} source: CRM sample selection\n\n${dealLines}`);
      setStep("anonymize");
      return;
    }
    setStep("input");
  };

  return (
    <main className="demo-wow-page">
      {!selectedMode && (
        <DemoWowHero
          modes={data.modes}
          activeMode={demoWowModeById(previewModeId)}
          activeModeId={previewModeId}
          onModeChange={setPreviewModeId}
          onStart={startFromHero}
          onSample={() => useSample(previewModeId)}
        />
      )}

      {selectedMode && (
        <section className="demo-wow-flow" aria-label={`${selectedMode.title} flow`}>
          {step !== "result" && <DemoStepRail step={step} />}

          {step === "source" && (
            <DemoSourcePanel
              mode={selectedMode}
              sourceType={sourceType}
              onSourceType={setSourceType}
              deals={data.sourceDeals || []}
              selectedDeals={selectedDeals}
              onToggleDeal={toggleSourceDeal}
              onUseSample={() => useSample(selectedMode.id)}
              onContinue={continueFromSource}
            />
          )}

          {step === "input" && (
            <DemoInputPanel
              mode={selectedMode}
              value={inputValue}
              onChange={setInputValue}
              onUseSample={() => useSample(selectedMode.id)}
              onContinue={() => canAnalyze && setStep("anonymize")}
              canContinue={canAnalyze}
            />
          )}

          {step === "anonymize" && (
            <AnonymizationPanel
              fields={data.sensitiveFields}
              usedSample={usedSample}
              onBack={() => setStep(sourceType === "crm" ? "source" : "input")}
              onAnalyze={() => setStep("loading")}
            />
          )}

          {step === "loading" && (
            <AnalysisLoading line={data.loadingLines[loadingIndex] || data.loadingLines[0]} />
          )}

          {step === "result" && (
            <DemoResult
              modeId={selectedMode.id}
              onReset={() => { setSelectedId(null); setStep("select"); }}
              onRunAgain={() => setStep("source")}
            />
          )}
        </section>
      )}
    </main>
  );
}

function DemoWowHero({ modes, activeMode, activeModeId, onModeChange, onStart, onSample }) {
  const preview = {
    deal: {
      input: "Proposal · €48k · closes this month",
      field: "Next step: follow up next week",
      score: "42 / 100",
      label: "Nudge sees high stall risk",
      metrics: [
        ["5", "proof gaps"],
        ["0", "buyer-owned steps"],
        ["1", "coaching prompt"],
      ],
      findings: [
        "This is not a real next step.",
        "The decision process is assumed.",
        "The buyer is interested, but not mobilized.",
      ],
      evidence: ["Economic buyer unknown", "Approval path missing", "Impact not quantified"],
    },
    meeting: {
      input: "Discovery call · strong interest · vague close",
      field: "Buyer: we need to align internally",
      score: "58 / 100",
      label: "Polite confusion detected",
      metrics: [
        ["3", "missed questions"],
        ["1", "weak next step"],
        ["4", "buyer signals"],
      ],
      findings: [
        "Interest was present, commitment was not.",
        "Budget timing surfaced but was not clarified.",
        "The meeting ended without a decision path.",
      ],
      evidence: ["Stakeholders unnamed", "Budget timing vague", "Decision event unclear"],
    },
    pipeline: {
      input: "12 open deals · €680k · this quarter",
      field: "Commit deals with activity but no proof",
      score: "51 / 100",
      label: "Pipeline risk detected",
      metrics: [
        ["42%", "no decision path"],
        ["6", "rep-owned steps"],
        ["4", "risky commits"],
      ],
      findings: [
        "Late-stage deals have no confirmed approval path.",
        "Next steps are logged, but buyer ownership is missing.",
        "Forecast confidence is running ahead of buyer proof.",
      ],
      evidence: ["Commit confidence inflated", "Buyer ownership weak", "Proof uneven by stage"],
    },
  }[activeModeId || "deal"];

  return (
    <section className="demo-wow-stage demo-wow-workbench">
      <header className="demo-wow-topbar">
        <span className="demo-wow-brand">
          <span className="demo-wow-brand-mark" aria-hidden="true"><i /><i /><i /></span>
          Nudge
        </span>
        <div className="demo-wow-top-actions">
          <span className="demo-wow-private"><Icon name="shield" size={13} /> Demo mode · anonymized</span>
          <button type="button" className="btn sm" onClick={onSample}>Run sample</button>
        </div>
      </header>

      <div className="demo-wow-hero">
        <div className="demo-wow-hero-copy">
          <span className="hero-eyebrow"><span className="glyph" /> Deal MRI demo</span>
          <h1>Diagnose a stalled deal in 60 seconds.</h1>
          <p>
            Start from a CRM note, transcript, or pipeline export. Nudge strips sensitive details, reads the buyer evidence, and returns the missing proof behind forecast risk.
          </p>

          <div className="demo-wow-mode-label">Analysis type</div>
          <DemoModeSelector modes={modes} selectedId={activeModeId} onSelect={onModeChange} />

          <div className="demo-wow-hero-proof-strip" aria-label={`${activeMode.title} preview metrics`}>
            {preview.metrics.map(([value, label]) => (
              <span key={label}>
                <b>{value}</b>
                <em>{label}</em>
              </span>
            ))}
          </div>

          <ol className="demo-wow-flow-preview" aria-label="Demo workflow">
            <li><span>1</span><b>Choose data</b><em>Sample, CRM selection, or paste</em></li>
            <li><span>2</span><b>Anonymize</b><em>Names and amounts can be masked</em></li>
            <li><span>3</span><b>Review MRI</b><em>Risk, proof gaps, next move</em></li>
          </ol>

          <div className="demo-wow-actions">
            <button type="button" className="btn accent lg" onClick={onSample}>
              Run sample {activeMode.title} <Icon name="arrow" size={15} />
            </button>
            <button type="button" className="btn lg" onClick={onStart}>Use my data</button>
          </div>
        </div>

        <div className="demo-wow-hero-panel" aria-label={`${activeMode.title} output preview`}>
          <div className="demo-wow-console-head">
            <span>Output preview</span>
            <b>{activeMode.title}</b>
          </div>

          <div className="demo-wow-preview-grid">
            <div className="demo-wow-reveal-card">
              <span className="eyebrow">Input snapshot</span>
              <div className="demo-wow-crm-line">
                <b>{preview.input}</b>
                <span>{preview.field}</span>
              </div>
            </div>

            <div className="demo-wow-score-preview">
              <span>Clarity score</span>
              <b>{preview.score.split(" ")[0]}</b>
              <em>{preview.label}</em>
            </div>
          </div>

          <div className="demo-wow-scan-line" aria-hidden="true"><span /></div>

          <div className="demo-wow-reveal-card is-nudge">
            <span className="eyebrow">Nudge diagnosis</span>
            <ul className="demo-wow-hero-findings">
              {preview.findings.map((finding) => <li key={finding}>{finding}</li>)}
            </ul>
            <div className="demo-wow-evidence-tags">
              {preview.evidence.map((item) => <span key={item}>{item}</span>)}
            </div>
          </div>

          <div className="demo-wow-next-preview">
            <span>Recommended manager question</span>
            <p>What evidence do we have that the buyer has committed to an internal next step?</p>
          </div>
        </div>
      </div>
    </section>
  );
}

function DemoModeSelector({ modes, selectedId, onSelect }) {
  return (
    <div className="demo-wow-mode-grid">
      {modes.map((mode) => (
        <button
          key={mode.id}
          type="button"
          className={`demo-wow-mode-card ${selectedId === mode.id ? "is-selected" : ""}`}
          onClick={() => onSelect(mode.id)}
        >
          <div className="demo-wow-mode-top">
            <div className="demo-wow-mode-icon" aria-hidden="true">
              <Icon name={mode.icon} size={17} />
            </div>
            <span>{mode.eyebrow}</span>
          </div>
          <b>{mode.title}</b>
          <small>{mode.description}</small>
        </button>
      ))}
    </div>
  );
}

function DemoStepRail({ step }) {
  const current = step === "source" || step === "input" ? 0 : step === "anonymize" || step === "loading" ? 1 : 2;
  return (
    <ol className="demo-wow-steps" aria-label="Demo steps">
      {["Choose data", "Anonymize & analyze", "Reveal report"].map((label, i) => (
        <li key={label} className={i === current ? "is-active" : i < current ? "is-done" : ""}>
          <span>{i + 1}</span>
          <b>{label}</b>
        </li>
      ))}
    </ol>
  );
}

function DemoSourcePanel({ mode, sourceType, onSourceType, deals, selectedDeals, onToggleDeal, onUseSample, onContinue }) {
  const selectedCount = selectedDeals.length;
  const isMeeting = mode.id === "meeting";
  return (
    <section className="demo-wow-panel demo-wow-source-panel">
      <div className="demo-wow-panel-head">
        <span className="eyebrow accent">{mode.title}</span>
        <h2>Start with the smallest useful data sample.</h2>
        <p>Import a document, connect CRM in demo mode, or select up to five opportunities. This prototype uses mock data only.</p>
      </div>

      <div className="demo-wow-source-grid">
        <button
          type="button"
          className={`demo-wow-source-card ${sourceType === "doc" ? "is-selected" : ""}`}
          onClick={() => onSourceType("doc")}
        >
          <Icon name="paperclip" size={18} />
          <b>Import doc</b>
          <span>{isMeeting ? "Transcript, call notes, or summary" : "Opportunity notes, proposal, or CRM export"}</span>
        </button>
        <button
          type="button"
          className={`demo-wow-source-card ${sourceType === "crm" ? "is-selected" : ""}`}
          onClick={() => onSourceType("crm")}
        >
          <Icon name="grid" size={18} />
          <b>Connect CRM</b>
          <span>Demo connection. No real Salesforce or HubSpot access.</span>
        </button>
        <button type="button" className="demo-wow-source-card" onClick={onUseSample}>
          <Icon name="sparkles" size={18} />
          <b>Use sample</b>
          <span>Skip setup and reveal the prepared diagnostic.</span>
        </button>
      </div>

      <div className="demo-wow-source-promise">
        <span><Icon name="shield" size={13} /> Names anonymized</span>
        <span><Icon name="target" size={13} /> Buyer proof preserved</span>
        <span><Icon name="clock" size={13} /> Result in under a minute</span>
      </div>

      {sourceType === "crm" && (
        <div className="demo-wow-deal-picker">
          <div className="demo-wow-deal-picker-head">
            <div>
              <h3>Select deals to scan</h3>
              <p>Choose up to 5. Nudge will preserve structure and anonymize names.</p>
            </div>
            <span>{selectedCount}/5 selected</span>
          </div>
          <div className="demo-wow-deal-list">
            {deals.map((deal) => {
              const selected = selectedDeals.includes(deal.id);
              const disabled = !selected && selectedDeals.length >= 5;
              return (
                <button
                  key={deal.id}
                  type="button"
                  className={`demo-wow-deal-row ${selected ? "is-selected" : ""}`}
                  onClick={() => onToggleDeal(deal.id)}
                  disabled={disabled}
                >
                  <span className="demo-wow-deal-check">{selected ? <Icon name="check" size={13} /> : null}</span>
                  <b>{deal.company}</b>
                  <span>{deal.stage}</span>
                  <em>{deal.amount}</em>
                  <small>{deal.signal}</small>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {sourceType === "doc" && (
        <div className="demo-wow-doc-drop">
          <Icon name="paperclip" size={18} />
          <div>
            <b>Drop a document here</b>
            <span>Prototype placeholder. Continue to paste content manually.</span>
          </div>
        </div>
      )}

      <div className="demo-wow-input-actions">
        <button type="button" className="btn" onClick={onUseSample}>Use sample data</button>
        <button type="button" className="btn accent" onClick={onContinue} disabled={sourceType === "crm" && selectedCount === 0}>
          {sourceType === "crm" ? "Analyze selected deals" : "Continue to paste"} <Icon name="arrow" size={14} />
        </button>
      </div>
    </section>
  );
}

function DemoInputPanel({ mode, value, onChange, onUseSample, onContinue, canContinue }) {
  const isPipeline = mode.id === "pipeline";
  return (
    <div className="demo-wow-input-grid">
      <section className="demo-wow-panel">
        <div className="demo-wow-panel-head">
          <span className="eyebrow accent">{mode.eyebrow}</span>
          <h2>{mode.inputTitle}</h2>
          <p>{mode.inputDescription}</p>
        </div>

        {isPipeline && (
          <div className="demo-wow-upload" role="button" tabIndex="0" aria-label="Upload CSV placeholder">
            <Icon name="paperclip" size={17} />
            <span>Drop a CSV here</span>
            <em>Placeholder only for this prototype</em>
          </div>
        )}

        <label className="demo-wow-textarea-label">
          <span>{isPipeline ? "Paste CSV text" : "Paste your own data"}</span>
          <textarea
            className="input demo-wow-textarea"
            value={value}
            onChange={(e) => onChange(e.target.value)}
            placeholder={mode.placeholder}
          />
        </label>

        <div className="demo-wow-input-actions">
          <button type="button" className="btn" onClick={onUseSample}>
            {mode.sampleCta}
          </button>
          <button type="button" className="btn accent" onClick={onContinue} disabled={!canContinue}>
            Continue <Icon name="arrow" size={14} />
          </button>
        </div>
      </section>

      <aside className="demo-wow-side-note">
        <span className="chip info"><Icon name="shield" size={12} /> Minimal access</span>
        <h3>No CRM integration required.</h3>
        <p>Paste notes, a transcript, or an export. Nudge reads deal structure and buyer signals before it needs system access.</p>
      </aside>
    </div>
  );
}

function AnonymizationPanel({ fields, usedSample, onBack, onAnalyze }) {
  const [confirmed, setConfirmed] = React.useState(false);
  const run = () => {
    setConfirmed(true);
    window.setTimeout(onAnalyze, 700);
  };
  return (
    <section className="demo-wow-panel demo-wow-anonymize">
      <div className="demo-wow-panel-head">
        <span className="eyebrow accent">Privacy layer</span>
        <h2>We detected sensitive information that can be anonymized before analysis.</h2>
        <p>{usedSample ? "The sample contains realistic fields so the privacy step feels like the live workflow." : "Sensitive details can be replaced while buying signals and deal structure stay intact."}</p>
      </div>
      <div className="demo-wow-field-grid">
        {fields.map((field) => (
          <span key={field} className="demo-wow-detected-field">
            <Icon name="check" size={13} /> {field}
          </span>
        ))}
      </div>
      {confirmed && (
        <div className="demo-wow-confirm">
          <Icon name="shield" size={15} />
          Sensitive details replaced. Buying signals and deal structure preserved.
        </div>
      )}
      <div className="demo-wow-input-actions">
        <button type="button" className="btn ghost" onClick={onBack}>Back</button>
        <button type="button" className="btn accent" onClick={run} disabled={confirmed}>
          Anonymize & analyze <Icon name="arrow" size={14} />
        </button>
      </div>
    </section>
  );
}

function AnalysisLoading({ line }) {
  return (
    <section className="demo-wow-loading" role="status" aria-live="polite">
      <span className="demo-wow-loading-mark" aria-hidden="true">
        <i /><i /><i />
      </span>
      <h2>{line}</h2>
      <p>Replacing sensitive details. Preserving buyer signals, deal structure, and progression evidence.</p>
    </section>
  );
}

function RiskScore({ label, score, riskLabel }) {
  return (
    <div className="demo-wow-score-card">
      <div>
        <span className="chip warn">{riskLabel}</span>
        <p>{label}</p>
      </div>
      <div className="demo-wow-score">
        <b>{score}</b>
        <span>/ 100</span>
      </div>
    </div>
  );
}

function InsightCard({ title, children }) {
  return (
    <article className="demo-wow-insight-card">
      <h4>{title}</h4>
      <p>{children}</p>
    </article>
  );
}

function RecommendedActionCard({ title = "Recommended next action", children }) {
  return (
    <section className="demo-wow-reco">
      <span className="eyebrow accent">{title}</span>
      <p>{children}</p>
    </section>
  );
}

function DemoResult({ modeId, onReset, onRunAgain }) {
  return (
    <div className="demo-wow-result-wrap">
      {modeId === "deal" && <DealMRIResult />}
      {modeId === "meeting" && <MeetingIntelligenceResult />}
      {modeId === "pipeline" && <PipelineMRIResult />}
      <div className="demo-wow-result-actions">
        <button type="button" className="btn" onClick={onRunAgain}>Analyze another input</button>
        <button type="button" className="btn ghost" onClick={onReset}>Back to modes</button>
      </div>
    </div>
  );
}

function DealMRIResult() {
  return (
    <section className="demo-wow-result demo-wow-deal-report">
      <header className="demo-wow-report-hero">
        <div>
          <span className="eyebrow accent">Deal MRI Result</span>
          <h2>ProspectCo is active, but not mobilized.</h2>
          <p>This deal can still close, but the current forecast is relying on seller activity instead of buyer proof.</p>
        </div>
        <div className="demo-wow-report-score">
          <span>Deal clarity</span>
          <b>42</b>
          <em>/ 100</em>
          <strong>High stall risk</strong>
        </div>
      </header>

      <section className="demo-wow-verdict">
        <span className="demo-wow-verdict-label">Main diagnosis</span>
        <p>This deal looks active, but there is no evidence of buyer commitment.</p>
      </section>

      <section className="demo-wow-proof-ledger" aria-label="Buyer proof ledger">
        <ProofLedgerItem status="missing" title="Economic buyer" detail="Referenced as probably interested, but not identified or engaged." />
        <ProofLedgerItem status="missing" title="Approval path" detail="No legal, procurement, security, or executive sign-off path is visible." />
        <ProofLedgerItem status="partial" title="Pain signal" detail="Forecast friction is real, but impact and urgency were not quantified." />
        <ProofLedgerItem status="missing" title="Buyer-owned action" detail="The next step is still a rep follow-up, not a buyer commitment." />
      </section>

      <section className="demo-wow-report-grid">
        <article className="demo-wow-proof-card is-risk">
          <span>CRM evidence</span>
          <b>Proposal sent. Meeting happened. Follow-up planned.</b>
          <p>Activity exists, but none of it proves the buyer is moving internally.</p>
        </article>
        <article className="demo-wow-proof-card">
          <span>Nudge read</span>
          <b>The next step is owned by the rep.</b>
          <p>"Follow up next week" does not say what the buyer will do, by when, or with whom.</p>
        </article>
        <article className="demo-wow-proof-card">
          <span>Forecast implication</span>
          <b>Commit confidence should be challenged.</b>
          <p>The close date is near, but the approval path and economic buyer are still unknown.</p>
        </article>
      </section>

      <section className="demo-wow-diagnostic-list">
        <h3>Three reasons this may stall</h3>
        {[
          ["Decision process", "Assumed, not confirmed", "No approver, buying committee, legal/procurement path, or internal validation step is visible."],
          ["Business impact", "Pain without numbers", "The buyer described friction, but no cost, urgency, or success metric is attached to it."],
          ["Buyer ownership", "Interest without motion", "The buyer has not committed to an internal next step or introduced another stakeholder."]
        ].map(([area, finding, detail]) => (
          <div key={area} className="demo-wow-diagnostic-row">
            <span>{area}</span>
            <b>{finding}</b>
            <p>{detail}</p>
          </div>
        ))}
      </section>

      <section className="demo-wow-missing-proof">
        <h3>Missing buyer proof</h3>
        {["Economic buyer unknown", "Approval path missing", "Buying event unclear", "Success criteria undefined", "Mutual action plan missing"].map((item) => (
          <span key={item}><Icon name="close" size={12} /> {item}</span>
        ))}
      </section>

      <section className="demo-wow-next-move">
        <div>
          <span className="eyebrow accent">Best next move</span>
          <h3>Turn the follow-up into a buyer-owned action.</h3>
        </div>
        <p>Before our next call, could you help me understand how a decision like this would typically get approved internally? Specifically, who needs to be involved, what criteria matter most, and what would need to happen for this to become a priority this quarter?</p>
      </section>

      <section className="demo-wow-manager-prompt">
        <span>Manager coaching prompt</span>
        <p>Ask the rep: what evidence do we have that the buyer has committed to an internal next step?</p>
      </section>
    </section>
  );
}

function ProofLedgerItem({ status, title, detail }) {
  const missing = status === "missing";
  return (
    <article className={`demo-wow-proof-ledger-item is-${status}`}>
      <span>{missing ? <Icon name="close" size={12} /> : <Icon name="check" size={12} />} {missing ? "Missing" : "Partial"}</span>
      <b>{title}</b>
      <p>{detail}</p>
    </article>
  );
}

function MeetingIntelligenceResult() {
  return (
    <section className="demo-wow-result">
      <div className="demo-wow-result-head">
        <span className="eyebrow accent">Meeting Intelligence Result</span>
        <h2>The buyer showed interest, but the meeting ended without a clear decision path.</h2>
      </div>
      <RiskScore label="Meeting Quality Score" score="58" riskLabel="Polite confusion detected" />
      <ResultBlock title="Buyer signals extracted">
        {[
          ["Pain mentioned", "Forecast reviews take too long and managers do not trust CRM data."],
          ["Urgency signal", "The team wants to improve this before next quarter."],
          ["Risk signal", "The buyer needs internal alignment but did not name the stakeholders."],
          ["Budget signal", "Budget timing was mentioned but not clarified."]
        ].map(([k, v]) => <SignalRow key={k} label={k} value={v} />)}
      </ResultBlock>
      <ResultBlock title="Missed follow-up moments">
        <MissedMoment quote="We need to align internally.">The rep should have asked who needs to be involved and what alignment means.</MissedMoment>
        <MissedMoment quote="This could be useful for Q3.">The rep should have clarified whether Q3 is a real buying event or a vague timeline.</MissedMoment>
        <MissedMoment quote="Managers are not always sure what is real in the forecast.">The rep should have quantified the cost of forecast uncertainty.</MissedMoment>
      </ResultBlock>
      <section className="demo-wow-next-quality">
        <span className="chip warn">Weak</span>
        <h3>Next-step quality</h3>
        <p>The next step is a follow-up, not a buyer commitment. There is no date, owner, internal action, or success criterion.</p>
      </section>
      <RecommendedActionCard>
        Hi Sophie, before I send the proposal around more widely, can we pin down what "align internally" means? Who needs to weigh in, what criteria will matter most, and is Q3 tied to a real decision event or just a possible timeline?
      </RecommendedActionCard>
    </section>
  );
}

function PipelineMRIResult() {
  const deals = (window.DEMO_WOW_DATA || {}).pipelineDeals || [];
  return (
    <section className="demo-wow-result">
      <div className="demo-wow-result-head">
        <span className="eyebrow accent">Pipeline MRI Result</span>
        <h2>Pipeline activity is hiding approval risk, weak buyer ownership, and inflated confidence.</h2>
      </div>
      <RiskScore label="Pipeline Clarity Score" score="51" riskLabel="Pipeline risk detected" />
      <ResultBlock title="Top-level insights">
        <ol className="demo-wow-number-list">
          <li>42% of late-stage deals have no confirmed decision process.</li>
          <li>6 deals have next steps, but none are buyer-owned.</li>
          <li>4 deals are forecasted this month with no clear economic buyer.</li>
          <li>Most stalled deals show activity, but no progression evidence.</li>
          <li>The team is logging meetings, but not capturing approval path or decision criteria.</li>
        </ol>
      </ResultBlock>
      <RiskyDealsTable deals={deals} />
      <section className="demo-wow-forecast-questions">
        <h3>Three questions for your next forecast review</h3>
        <ol>
          <li>Which deals have buyer-owned next steps?</li>
          <li>Which committed deals have a confirmed approval path?</li>
          <li>Which late-stage deals have quantified business impact?</li>
        </ol>
      </section>
    </section>
  );
}

function ResultBlock({ title, children }) {
  return (
    <section className="demo-wow-result-block">
      <h3>{title}</h3>
      <div className="demo-wow-result-grid">{children}</div>
    </section>
  );
}

function Checklist({ title, items }) {
  return (
    <section className="demo-wow-checklist">
      <h3>{title}</h3>
      <ul>
        {items.map((item) => (
          <li key={item}><Icon name="close" size={13} /> {item}</li>
        ))}
      </ul>
    </section>
  );
}

function SignalRow({ label, value }) {
  return (
    <div className="demo-wow-signal-row">
      <b>{label}</b>
      <span>{value}</span>
    </div>
  );
}

function MissedMoment({ quote, children }) {
  return (
    <article className="demo-wow-missed">
      <span>Buyer said</span>
      <q>{quote}</q>
      <b>Nudge insight</b>
      <p>{children}</p>
    </article>
  );
}

function RiskyDealsTable({ deals }) {
  return (
    <section className="demo-wow-table-card">
      <h3>Risky deals</h3>
      <div className="demo-wow-table-wrap">
        <table className="demo-wow-table">
          <thead>
            <tr>
              <th>Deal</th>
              <th>Stage</th>
              <th>Amount</th>
              <th>Close date</th>
              <th>Hidden risk</th>
              <th>Recommended action</th>
            </tr>
          </thead>
          <tbody>
            {deals.map((deal) => (
              <tr key={deal.deal}>
                <td><b>{deal.deal}</b></td>
                <td>{deal.stage}</td>
                <td>{deal.amount}</td>
                <td>{deal.closeDate}</td>
                <td><span className="chip warn">{deal.hiddenRisk}</span></td>
                <td>{deal.action}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

window.DemoWowPage = DemoWowPage;
