/* eslint-disable */
const { useState, useEffect, useRef, useMemo } = React;

const SECTIONS = [
  { id: "fit",       num: "01", name: "Market Fit",            meta: "$15–20B" },
  { id: "audience",  num: "02", name: "Target Audience",       meta: "5 seg." },
  { id: "value",     num: "03", name: "Value Propositions",    meta: "5 drv." },
  { id: "moats",     num: "04", name: "Competitive Advantages",meta: "5 moats" },
  { id: "channels",  num: "05", name: "Channels",              meta: "3 phases" },
  { id: "cac",       num: "06", name: "CAC Ranges",            meta: "$18–35" },
  { id: "roadmap",   num: "07", name: "Execution Roadmap",     meta: "12 mo." },
  { id: "metrics",   num: "08", name: "Success Metrics",       meta: "5 KPIs" },
];

const SUGGESTED = [
  "Tighten messaging for solopreneurs",
  "Add a LATAM expansion sub-plan",
  "Re-cost CAC for a $5/mo entry tier",
  "Rewrite Section 03 in plain language",
  "Stress-test against a Zapier price cut",
];

// ── Template fallbacks ─────────────────────────────────────────────────────
const TPL = {
  market_fit: { score: 9, verdict: "Excellent", summary: "The mid-market sits between hobbyist tools and enterprise automation suites — an audience large enough to scale, neglected enough to win.", strengths: [], risks: [] },
  market_size: { tam: "$15–20B", cagr: "23.4%", users: "2.1M", gap: "3.4×" },
  target_segments: [
    { name: "Indie hackers & solopreneurs", subtitle: "Side-project builders, <$500k ARR", tam: "$3–5B", priority: "Highest" },
    { name: "Early-stage startups (2–10)",  subtitle: "Pre-Series A, bootstrapped",       tam: "$5–8B", priority: "Highest" },
    { name: "Freelancers / agencies",       subtitle: "Build & resell client workflows",  tam: "$2–3B", priority: "High" },
    { name: "Dev-focused teams (10–50)",    subtitle: "Internal automation, API-first",   tam: "$3–4B", priority: "High" },
    { name: "Citizen developers",           subtitle: "Non-technical ops automators",     tam: "$2–3B", priority: "Medium" },
  ],
  value_propositions: [
    { title: "AI-assisted pipeline building", description: "Describe the workflow in plain language; the model emits the graph, error handling and monitoring.", tag: "Saves 5–10 hrs / pipeline" },
    { title: "Honest pricing",                description: "Pay-as-you-go runs, not seat-priced bloat. Predictable, 50–70% cheaper at scale than Zapier.",    tag: "Budget-shaped" },
    { title: "Developer-first",               description: "Webhooks, custom code, version control, real auth. Built for people who read changelogs.",          tag: "API native" },
    { title: "No-code when you want it",      description: "Hybrid surface — drag a node or write a function. Neither audience is the second-class citizen.",  tag: "Low ceiling, no walls" },
    { title: "Time-to-first-value",           description: "From signup to running pipeline in under nine minutes (median across 41 onboarding sessions).",    tag: "Median 8m 42s" },
  ],
  competitive_advantages: [
    { name: "AI-first UX",            strength: 78, durability: "3–6 mo. lead",   description: "Natural-language pipeline authoring is non-trivial to graft onto node editors." },
    { name: "Cost structure",         strength: 88, durability: "Ongoing",         description: "Lean infra + per-run billing — competitors must rebuild billing to match." },
    { name: "Developer velocity",     strength: 72, durability: "High switch-cost",description: "Once integrated, embedded webhooks and code blocks become load-bearing." },
    { name: "Community gravity",      strength: 54, durability: "Medium",          description: "Indie Hackers, ShipFast, r/SaaS — owned mind-share compounds slowly." },
    { name: "Use-case template lib",  strength: 47, durability: "Replicable",      description: "Easy to clone, but first-mover keeps the SEO real estate." },
    { name: "Pipeline data flywheel", strength: 64, durability: "Network effect",  description: "More pipelines → better model suggestions → fewer drop-offs." },
  ],
  channels: [
    { name: "Content + SEO",   priority: "P0", tactic: "Long-form: 'n8n alternative', indie-dev API how-tos.", cac: "$3–15" },
    { name: "ProductHunt",     priority: "P0", tactic: "Coordinated launch w/ AI-pipeline demo + 24h Q&A.",    cac: "$5–25" },
    { name: "Dev communities", priority: "P0", tactic: "Indie Hackers, Dev.to, HN, X — seed by 6 founders.",  cac: "$2–10" },
    { name: "YouTube",         priority: "P1", tactic: "5-minute automation series + walkthroughs.",           cac: "$8–20" },
    { name: "Reddit",          priority: "P1", tactic: "r/SaaS, r/webdev, r/entrepreneur — value-first.",      cac: "$6–18" },
  ],
  cac: { blended_low: 18, blended_high: 35, best_channel: "Organic / community", tagline: "Three channels pay back in weeks." },

  phases: [
    { when: "Months 1–3", name: "Launch & Awareness",  milestones: ["Ship 3–5 cornerstone SEO posts", "ProductHunt launch w/ demo video", "Seed Indie Hackers, Dev.to, Reddit", "20 first-customer interviews"], target: "100–500 signups · ~$5–8 CAC" },
    { when: "Months 3–6", name: "Scale & Optimise",    milestones: ["Google Ads on intent keywords", "Referral program live — credits-based", "YouTube series · 5–10 walkthroughs", "Email list to 500+"], target: "500–1.5k signups · $15–20 CAC · $5–10k MRR" },
    { when: "Months 6–12",name: "Growth & Expansion",  milestones: ["Expand paid to LinkedIn + Reddit", "Affiliate & partnership program", "Free → paid conversion funnel", "Community-driven roadmap"], target: "5k+ cumulative · $18–30 CAC · $30–100k MRR" },
  ],

  kpis: [
    { kpi: "CAC payback period",     target: "< 3 mo",   data: [4.8, 4.5, 4.2, 3.6, 3.1, 2.8, 2.6] },
    { kpi: "LTV : CAC ratio",        target: "> 3 : 1",  data: [1.2, 1.6, 1.9, 2.3, 2.7, 3.0, 3.4] },
    { kpi: "Free → paid conversion", target: "2 – 5 %",  data: [0.8, 1.1, 1.5, 1.9, 2.4, 2.8, 3.1] },
    { kpi: "NPS",                    target: "> 50",     data: [22, 28, 31, 36, 41, 47, 53] },
    { kpi: "Viral coefficient",      target: "> 1.1",    data: [0.4, 0.5, 0.6, 0.8, 0.9, 1.05, 1.18] },
    { kpi: "Activation rate",        target: "> 60 %",   data: [38, 42, 45, 51, 55, 58, 63] },
  ],
  north_star: {
    metric: "Monthly automation runs",
    definition: "Monthly automation runs created by users — the only metric that captures stickiness, value, and growth in one number.",
    target: "Tracked weekly · cohorted by signup month"
  },
};

function fitVerdict(score) {
  if (score >= 8) return "Excellent";
  if (score >= 6) return "Good";
  if (score >= 4) return "Fair";
  return "Weak";
}

function priorityDot(p) {
  if (p === "Highest") return "red";
  if (p === "High")    return "orange";
  return "yellow";
}

// ───────────────────────────── Brief / Header
function BriefCard({ workspace = {}, planData }) {
  const analysis = planData?.market_analysis;
  const {
    product = "Your product",
    stage   = "Pre-launch",
    region  = "Global EN",
    budget  = "—",
    tone    = "Editorial",
  } = workspace;

  const tagline = analysis?.tagline || workspace.description || "";

  return (
    <div className="brief">
      <div className="brief-label">Marketing Plan · v3.2</div>
      <h1>
        <em>{product}</em>
        {tagline ? <> — {tagline}</> : ""}
      </h1>
      <div className="brief-meta">
        <div><b>STAGE</b><br/>{stage}</div>
        <div><b>REGION</b><br/>{region}</div>
        <div><b>BUDGET</b><br/>{budget}</div>
        <div><b>TONE</b><br/>{tone}</div>
        <div><b>PREPARED</b><br/>May 15, 2026</div>
      </div>
    </div>
  );
}

// ───────────────────────────── 01 Market Fit
function SectionFit({ data }) {
  const fit  = data?.market_fit  || TPL.market_fit;
  const size = data?.market_size || TPL.market_size;
  const verdictClass = fit.score >= 8 ? "" : fit.score >= 6 ? "" : "warn";

  return (
    <section className="section" id="fit">
      <header className="section-head">
        <div className="section-num">§01</div>
        <h2 className="section-title">Market Fit</h2>
        <span className={`section-verdict ${verdictClass}`}>Verdict · {fit.verdict || fitVerdict(fit.score)}</span>
      </header>

      <p className="lede">{fit.summary}</p>

      <div className="stat-strip">
        <div className="stat">
          <div className="stat-label">TAM</div>
          <div className="stat-value">{size.tam}</div>
          <div className="stat-sub">workflow + iPaaS</div>
        </div>
        <div className="stat">
          <div className="stat-label">CAGR</div>
          <div className="stat-value">{size.cagr}</div>
          <div className="stat-sub">2024 → 2029</div>
        </div>
        <div className="stat">
          <div className="stat-label">Addressable users</div>
          <div className="stat-value">{size.users}</div>
          <div className="stat-sub">primary ICP</div>
        </div>
        <div className="stat">
          <div className="stat-label">Pricing gap</div>
          <div className="stat-value">{size.gap}</div>
          <div className="stat-sub">vs. incumbents</div>
        </div>
      </div>

      {fit.strengths?.length > 0 && (
        <p className="body">
          <strong>Strengths: </strong>{fit.strengths.join(" · ")}
        </p>
      )}
      {fit.risks?.length > 0 && (
        <p className="body">
          <strong>Risks: </strong>{fit.risks.join(" · ")}
        </p>
      )}
    </section>
  );
}

// ───────────────────────────── 02 Audience
function SectionAudience({ data }) {
  const rows = data?.target_segments || TPL.target_segments;

  return (
    <section className="section" id="audience">
      <header className="section-head">
        <div className="section-num">§02</div>
        <h2 className="section-title">Target Audience</h2>
        <span className="section-verdict">{rows.length} primary segments</span>
      </header>
      <p className="lede">
        Concentric rings of buyers — every outer ring expands but raises CAC.
        The two innermost own the first six months.
      </p>

      <div className="aud-table">
        <div className="aud-row head">
          <div>#</div><div>Segment</div><div>Defining trait</div><div>TAM</div><div>Priority</div>
        </div>
        {rows.map((r, i) => (
          <div key={i} className="aud-row">
            <div className="idx">{String(i + 1).padStart(2, "0")}</div>
            <div className="seg">{r.name}</div>
            <div className="seg" style={{ fontWeight: 400 }}>
              <span style={{ color: "var(--muted)", fontSize: 12 }}>{r.subtitle}</span>
            </div>
            <div className="tam">{r.tam}</div>
            <div className="pri">
              <span className={`dot ${priorityDot(r.priority)}`}></span>
              <span className="pri-label">{r.priority}</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────────── 03 Value
function SectionValue({ data }) {
  const cards = data?.value_propositions || TPL.value_propositions;

  return (
    <section className="section" id="value">
      <header className="section-head">
        <div className="section-num">§03</div>
        <h2 className="section-title">Value Propositions</h2>
        <span className="section-verdict">{cards.length} drivers</span>
      </header>
      <p className="lede">
        One sentence, five proofs. The wedge is <em>speed × price</em>; the
        retention story is everything else.
      </p>
      <div className="vp-grid">
        {cards.map((c, i) => (
          <div className="vp-card" key={i}>
            <div className="vp-num">{String(i + 1).padStart(2, "0")}</div>
            <h4>{c.title}</h4>
            <p>{c.description}</p>
            <span className="vp-tag">{c.tag}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────────── 04 Moats
function SectionMoats({ data }) {
  const moats = data?.competitive_advantages || TPL.competitive_advantages;
  const strong = moats.filter(m => m.strength >= 70).length;

  return (
    <section className="section" id="moats">
      <header className="section-head">
        <div className="section-num">§04</div>
        <h2 className="section-title">Competitive Advantages</h2>
        <span className="section-verdict warn">{strong} strong, {moats.length - strong} growing</span>
      </header>
      <p className="lede">
        Real moats compound if the first thousand users stick — the rest of
        the plan is about getting them there.
      </p>
      <div className="moats">
        {moats.map((m, i) => (
          <div className="moat" key={i}>
            <div className="moat-head">
              <span className="moat-name">{m.name}</span>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)" }}>{m.strength}</span>
            </div>
            <div className="moat-bar">
              <div className="moat-bar-fill" style={{ "--w": `${m.strength}%`, width: `${m.strength}%` }}></div>
            </div>
            <div className="moat-desc">{m.description}</div>
            <div className="moat-foot"><span>strength</span><span>{m.durability}</span></div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────────── 05 Channels
function SectionChannels({ data, campaignData }) {
  const p1Rows = data?.channels || TPL.channels;

  // Build phases from campaign data or template
  const phases = campaignData?.phases
    ? {
        P1: { label: campaignData.phases[0]?.name || "Phase 1 · Awareness", meta: campaignData.phases[0]?.when || "Months 1–3", rows: p1Rows },
        P2: { label: campaignData.phases[1]?.name || "Phase 2 · Scale",     meta: campaignData.phases[1]?.when || "Months 3–12", rows: [
          { name: "Google search ads", priority: "P0", tactic: "High-intent: 'cheap workflow automation', 'zapier alt'.", cac: "$15–40" },
          { name: "LinkedIn",          priority: "P1", tactic: "Founders, ops leads, fractional CTOs.",                   cac: "$25–60" },
          { name: "Founder collabs",   priority: "P1", tactic: "Podcasts, newsletters, Indie Hackers AMA.",               cac: "$10–25" },
          { name: "Partnerships",      priority: "P2", tactic: "Stripe, Airtable, Resend — co-marketing.",                cac: "$5–15" },
        ]},
        P3: { label: campaignData.phases[2]?.name || "Phase 3 · Maturity", meta: campaignData.phases[2]?.when || "Year 2+", rows: [
          { name: "Organic SEO",      priority: "P0", tactic: "Rank for category terms + comparison long-tail.", cac: "$3–8" },
          { name: "Referral program", priority: "P0", tactic: "$50–200 credits / activated invite.",             cac: "$5–15" },
          { name: "Freemium loops",   priority: "P1", tactic: "Public templates → signup → conversion.",         cac: "$8–20" },
          { name: "PLG sales touch",  priority: "P1", tactic: "Account expansion above 10-seat threshold.",      cac: "$20–40" },
        ]},
      }
    : {
        P1: { label: "Phase 1 · Awareness", meta: "Months 1–3",  rows: p1Rows },
        P2: { label: "Phase 2 · Scale",     meta: "Months 3–12", rows: [
          { name: "Google search ads", priority: "P0", tactic: "High-intent: 'cheap workflow automation', 'zapier alt'.", cac: "$15–40" },
          { name: "LinkedIn",          priority: "P1", tactic: "Founders, ops leads, fractional CTOs.",                   cac: "$25–60" },
          { name: "Founder collabs",   priority: "P1", tactic: "Podcasts, newsletters, Indie Hackers AMA.",               cac: "$10–25" },
        ]},
        P3: { label: "Phase 3 · Maturity", meta: "Year 2+", rows: [
          { name: "Organic SEO",      priority: "P0", tactic: "Rank for category terms + comparison long-tail.", cac: "$3–8" },
          { name: "Referral program", priority: "P0", tactic: "$50–200 credits / activated invite.",             cac: "$5–15" },
        ]},
      };

  const [phase, setPhase] = useState("P1");
  const cur = phases[phase];

  return (
    <section className="section" id="channels">
      <header className="section-head">
        <div className="section-num">§05</div>
        <h2 className="section-title">Channels</h2>
        <span className="section-verdict">Phased</span>
      </header>
      <p className="lede">
        Spend follows attention. Months 1–3 are unpaid; paid only proves
        what community already validated.
      </p>

      <div className="phase-tabs">
        {Object.entries(phases).map(([k, v]) => (
          <button key={k} className={`phase-tab ${phase === k ? "active" : ""}`} onClick={() => setPhase(k)}>
            {v.label}
            <span className="ph-meta">{v.meta}</span>
          </button>
        ))}
      </div>

      <div className="channels">
        <div className="ch-row head">
          <div>#</div><div>Channel</div><div>Tactic</div><div>Pri.</div>
          <div style={{ textAlign: "right" }}>CAC</div>
        </div>
        {cur.rows.map((r, i) => (
          <div key={i} className="ch-row">
            <div className="idx">{String(i + 1).padStart(2, "0")}</div>
            <div className="name">{r.name}</div>
            <div className="tac">{r.tactic}</div>
            <div className={`pri-badge pri-${r.priority}`}>{r.priority}</div>
            <div className="cac-cell">{r.cac}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────────── 06 CAC
function SectionCAC({ data }) {
  const cacData = data?.cac || TPL.cac;
  const channels = data?.channels || TPL.channels;

  // Build bar items from channel data
  const allItems = [
    ...channels.map(c => {
      const [lo, hi] = (c.cac || "$5–20").replace(/\$/g, "").split("–").map(Number);
      return { label: c.name, lo: lo || 5, hi: hi || 20, accent: c.priority === "P0" };
    }),
    { label: "LinkedIn ads",    lo: 25, hi: 60, accent: false },
    { label: "Meta / Facebook", lo: 20, hi: 50, accent: false },
    { label: "Email / webinars",lo: 0,  hi: 5,  accent: true  },
  ];
  const max = 60;

  return (
    <section className="section" id="cac">
      <header className="section-head">
        <div className="section-num">§06</div>
        <h2 className="section-title">CAC by Channel</h2>
        <span className="section-verdict">Blended ${cacData.blended_low}–{cacData.blended_high}</span>
      </header>
      <p className="lede">{cacData.tagline}</p>

      <div className="cac-list">
        {allItems.map((item, i) => {
          const left  = (item.lo / max) * 100;
          const width = ((item.hi - item.lo) / max) * 100;
          return (
            <div className="cac-item" key={i}>
              <div className="label">{item.label}</div>
              <div className="cac-track">
                <div className={`cac-track-fill ${item.accent ? "accent" : ""}`}
                  style={{ left: `${left}%`, width: `${Math.max(width, 2)}%` }} />
              </div>
              <div className="cac-amt">${item.lo}–{item.hi}</div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ───────────────────────────── 07 Roadmap
function SectionRoadmap({ data }) {
  const blocks = data?.phases
    ? data.phases.map(p => ({
        when:   p.when,
        phase:  p.name,
        items:  (p.milestones || []).map(t => ({ t, d: false })),
        target: p.target,
      }))
    : TPL.phases.map(p => ({
        when:   p.when,
        phase:  p.name,
        items:  p.milestones.map(t => ({ t, d: false })),
        target: p.target,
      }));

  return (
    <section className="section" id="roadmap">
      <header className="section-head">
        <div className="section-num">§07</div>
        <h2 className="section-title">Execution Roadmap</h2>
        <span className="section-verdict">12 months</span>
      </header>
      <p className="lede">
        A staged plan, not a sprint. Each phase has one job; the next phase
        won't start until the previous one's CAC proves stable.
      </p>
      <div className="roadmap">
        {blocks.map((b, idx) => (
          <div className="rm-block" key={idx}>
            <div>
              <div className="rm-when">{b.when}</div>
              <div className="rm-phase">{b.phase}</div>
            </div>
            <div className="rm-content">
              <div className="rm-checklist">
                {b.items.map((it, j) => (
                  <ToggleItem key={j} text={it.t} initial={it.d} />
                ))}
              </div>
              <div className="rm-targets">Target · <b>{b.target}</b></div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function ToggleItem({ text, initial }) {
  const [d, setD] = useState(!!initial);
  return (
    <div className="rm-item">
      <div className={`rm-check ${d ? "done" : ""}`} onClick={() => setD(!d)}></div>
      <div style={{ textDecoration: d ? "line-through" : "none", opacity: d ? 0.65 : 1 }}>{text}</div>
    </div>
  );
}

// ───────────────────────────── 08 Metrics
function Sparkline({ data, color = "var(--accent)" }) {
  const w = 100, h = 32;
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
    return `${x},${y}`;
  }).join(" ");
  const last = pts.split(" ").pop().split(",");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="kpi-spark" preserveAspectRatio="none">
      <polyline fill="none" stroke={color} strokeWidth="1.4" points={pts}
        vectorEffect="non-scaling-stroke" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="2.4" fill={color} />
    </svg>
  );
}

// Generate a simple ascending/descending sparkline from a target string
function fakeSparkline(target) {
  const up = [28, 34, 42, 51, 58, 64, 71];
  const down = [4.8, 4.2, 3.6, 3.1, 2.8, 2.5, 2.2];
  return target.startsWith("<") ? down : up;
}

function SectionMetrics({ data }) {
  const kpis = data?.kpi_dashboard
    ? data.kpi_dashboard.slice(0, 6).map(k => ({
        name: k.kpi,
        target: k.target,
        data: fakeSparkline(k.target),
      }))
    : TPL.kpis.map(k => ({ name: k.kpi, target: k.target, data: k.data }));

  const north = data?.north_star_metric || TPL.north_star;

  return (
    <section className="section" id="metrics">
      <header className="section-head">
        <div className="section-num">§08</div>
        <h2 className="section-title">Success Metrics</h2>
        <span className="section-verdict">{kpis.length} KPIs · 1 north star</span>
      </header>
      <p className="lede">
        Six dials, one star. If any dial drifts two weeks below target, the
        roadmap pauses and we triage before adding more spend.
      </p>

      <div className="kpi-grid">
        {kpis.map(k => (
          <div className="kpi" key={k.name}>
            <div className="kpi-name">{k.name}</div>
            <div className="kpi-target">target · <b>{k.target}</b></div>
            <Sparkline data={k.data} />
          </div>
        ))}
      </div>

      <div className="north">
        <div className="north-label">North star</div>
        <div className="north-text">{north.definition}</div>
        <div className="north-meta">{north.target}</div>
      </div>

      <div className="summary">
        <h4>Why we think this works</h4>
        <div className="sum-list">
          <div className="sum-item"><div><b>Clear market gap.</b> Affordable + AI-assisted automation is unowned.</div></div>
          <div className="sum-item"><div><b>Aligned audience.</b> Cost-sensitive indie devs match the price story.</div></div>
          <div className="sum-item"><div><b>Sub-$20 CAC.</b> Reachable through communities before paid.</div></div>
          <div className="sum-item"><div><b>Strong unit economics.</b> $15–30 MRR, 2–3 month payback.</div></div>
          <div className="sum-item"><div><b>Defensible differentiators.</b> AI UX, developer focus, honest pricing.</div></div>
        </div>
      </div>

      <div className="doc-foot">
        <span>getplan.today · plan auto-generated</span>
        <span>regenerated · {new Date().toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })}</span>
      </div>
    </section>
  );
}

Object.assign(window, {
  SECTIONS, SUGGESTED,
  BriefCard, SectionFit, SectionAudience, SectionValue, SectionMoats,
  SectionChannels, SectionCAC, SectionRoadmap, SectionMetrics,
});
