/* global React, ArrowRight */

/* ---------------------- §3 The crew ---------------------- */

const CrewCard = ({ role, title, sub, body, price, art }) => (
  <div className="crew-card">
    <div className="role">
      {role}
      {price && <span className="price-pill">{price}</span>}
    </div>
    <h4>{title}</h4>
    {sub && <div className="sub">{sub}</div>}
    <p>{body}</p>
    {art && <div className="crew-art">{art}</div>}
  </div>
);

/* Tiny product-fragment artifacts. Each accepts content props so audience variants
   can supply their own copy; defaults reflect the D2C variant. */
const KPI_DEFAULT = [
  { l: "Revenue", v: "$18.4k", d: "↑ 12%", dir: "up" },
  { l: "ROAS", v: "2.1×", d: "↓ 18%", dir: "down" },
  { l: "Tickets", v: "47", d: "↑ 6", dir: "up" },
];
const ArtKPI = ({ items = KPI_DEFAULT }) => (
  <div className="kpi-strip">
    {items.map((k, i) => (
      <div className="kpi" key={i}>
        <span className="l">{k.l}</span>
        <span className="v">{k.v}</span>
        <span className={"d " + k.dir}>{k.d}</span>
      </div>
    ))}
  </div>
);
const ArtMsg = ({ text = "Hi Marta, so sorry to see the damage. I've issued a full refund and dispatched a replacement on priority…" }) => (
  <div className="mini-msg">{text}</div>
);
const STOCK_DEFAULT = [
  { name: "SKU-A20 · Linen Tee", qty: "12 left", pct: 14, low: true },
  { name: "SKU-B07 · Wool Throw", qty: "148 left", pct: 72, low: false },
];
const ArtStock = ({ items = STOCK_DEFAULT }) => (
  <div className="stock-bar">
    {items.map((s, i) => (
      <React.Fragment key={i}>
        <div className="row"><span>{s.name}</span><b>{s.qty}</b></div>
        <div className="bar"><div className={"fill" + (s.low ? " low" : "")} style={{ width: s.pct + "%" }} /></div>
      </React.Fragment>
    ))}
  </div>
);
const ArtSpark = () => (
  <svg className="spark" viewBox="0 0 200 36" preserveAspectRatio="none" fill="none">
    <path d="M0 22 L20 18 L40 24 L60 20 L80 14 L100 16 L120 22 L140 28 L160 26 L180 30 L200 32"
      stroke="var(--brand)" strokeWidth="1.5" />
    <path d="M0 22 L20 18 L40 24 L60 20 L80 14 L100 16 L120 22 L140 28 L160 26 L180 30 L200 32 L200 36 L0 36 Z"
      fill="var(--brand-wash)" />
    <circle cx="80" cy="14" r="2.5" fill="var(--brand)" />
  </svg>
);
const EMAIL_DEFAULT = [
  { label: "Triggered · Abandoned cart", kind: "start" },
  { label: "Wait 30m", kind: "wait" },
  { label: "Send: “Still thinking?”", kind: "send" },
];
const ArtEmail = ({ nodes = EMAIL_DEFAULT }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
    {nodes.map((n, i) => (
      <div className="email-node" key={i} style={n.kind === "start" ? null : { paddingLeft: 16 }}>
        {n.kind === "wait"
          ? <span className="line" />
          : <span className="dot" style={n.kind === "send" ? { background: "var(--green)" } : null} />}
        <span>{n.label}</span>
      </div>
    ))}
  </div>
);
const ArtThumbs = () => (
  <div className="thumb-row">
    <div className="th brand" />
    <div className="th" />
    <div className="th" />
    <div className="th" />
  </div>
);
const CAPTIONS_DEFAULT = [
  "soft-launch energy. swatch drop friday, link in bio",
  "the linen tee restock no one asked for (everyone wanted)",
  "we made the throw heavier. it's better. you'll see.",
];
const ArtCaptions = ({ items = CAPTIONS_DEFAULT }) => (
  <div className="caption-stack">
    {items.map((c, i) => <div className="c" key={i}>{c}</div>)}
  </div>
);

const CREW_VARIANTS = {
  startups: {
    label: "Early-stage startup",
    hint: "GTM · content · outbound",
    lead: "Seed-stage SaaS doesn't need twenty hires, it needs a go-to-market engine. Octocrew runs the three roles a founder usually fills alone: GTM ops, content and SEO, outbound.",
    starter: {
      title: "Starter trio",
      price: <React.Fragment>From <b>€1,500/mo</b> · three agents · all approvals in Slack</React.Fragment>,
      cards: [
        { role: "GTM Ops", title: "The marketing engine.", sub: "Launches · channels · campaigns", body: "Plans launches, runs the content and channel calendar, briefs and ships campaigns across your stack. The marketing hire you can't afford yet.", art: <ArtCaptions items={[
          "Launch · v2 pricing page · Tue 9am",
          "Channel calendar · 6 posts queued",
          "Campaign · 'AI for ops' · live",
        ]} /> },
        { role: "Content & SEO", title: "Inbound that compounds.", sub: "Blog · SEO · thought leadership", body: "Writes founder-voice posts and SEO briefs, ships on-page, tracks rankings. Turns your expertise into pipeline while you build.", art: <ArtThumbs /> },
        { role: "Outbound", title: "Pipeline on tap.", sub: "Lists · sequences · CRM", body: "Builds target lists, runs personalized cold sequences, keeps the CRM clean, books replies into your calendar. Plugs the SDR gap.", art: <ArtEmail nodes={[
          { label: "Triggered · ICP match", kind: "start" },
          { label: "Enrich · LinkedIn signal", kind: "wait" },
          { label: "Send: opener", kind: "send" },
        ]} /> },
      ],
    },
    addons: {
      title: "Add specialists as the round funds them",
      price: "Modular · cancel any specialist anytime",
      cards: [
        { role: "Lifecycle", title: "Activate. Retain.", body: "Onboarding emails, activation nudges, churn-save flows. Turns signups into active, paying users.", art: <ArtEmail nodes={[
          { label: "Signup · day 0", kind: "start" },
          { label: "No activation · 48h", kind: "wait" },
          { label: "Send · nudge", kind: "send" },
        ]} /> },
        { role: "Social", title: "Founder-voice cadence.", body: "Drafts LinkedIn and X posts in your voice, schedules cadence, surfaces engagement worth replying to in your inbox.", art: <ArtCaptions items={[
          "shipped two features today. one nobody asked for. it'll change everything.",
          "the dashboard is finally good. screenshots tomorrow.",
          "we hit $1k MRR. inception unlocked.",
        ]} /> },
        { role: "Ads", title: "Paid, when funded.", body: "Spins up and manages paid acquisition across Google and Meta. Drafts creative, tracks CAC, scales what converts.", art: <ArtSpark /> },
        { role: "Investor Updates", title: "Monthly, on time.", body: "Drafts the monthly investor update from KPIs, wins, asks, and burn. You edit, never author from blank.", art: <ArtKPI items={[
          { l: "MRR", v: "$9.2k", d: "↑ 11%", dir: "up" },
          { l: "Burn", v: "$28k", d: "↓ 6%", dir: "up" },
          { l: "Runway", v: "14 mo", d: "↑ 1mo", dir: "up" },
        ]} /> },
      ],
    },
  },
  d2c: {
    label: "E-com business",
    hint: "Store · support · ads",
    lead: "The three roles every store is always behind on: keeping the store running, answering customers, and managing spend. Octocrew runs them from day one. Add content, email, and SEO as you grow.",
    starter: {
      title: "Starter trio",
      price: <React.Fragment>From <b>€1,500/mo</b> · three agents · all approvals in Slack</React.Fragment>,
      cards: [
        { role: "E-commerce Ops", title: "The store, handled.", sub: "Shopify · stock · themes", body: "Daily sales pulse, restock alerts, preorder toggles, product and theme updates. Closes the gap between “we should fix that” and “it's done.”", art: <ArtStock /> },
        { role: "Customer Support", title: "Drafts. Approves. Sends.", sub: "Brand voice · PII redacted", body: "Drafts ticket replies in your brand voice with full order context. PII redacted. Refunds and edge cases escalate to humans. Earns send rights one workflow at a time.", art: <ArtMsg /> },
        { role: "Ads Manager", title: "Builds. Launches. Scales.", sub: "Meta · Google · TikTok", body: "Builds campaigns and creative, launches, tracks ROAS daily, pauses losers and reallocates budget to what's working.", art: <ArtKPI items={[
          { l: "ROAS", v: "2.1×", d: "↑ 0.3", dir: "up" },
          { l: "Spend", v: "$6.2k", d: "on plan", dir: "up" },
          { l: "CPA", v: "$24", d: "↓ 9%", dir: "up" },
        ]} /> },
      ],
    },
    addons: {
      title: "Add specialists as you grow",
      price: "Modular · cancel any specialist anytime",
      cards: [
        { role: "Email & Retention", title: "Klaviyo-native.", body: "Builds campaigns and flows, abandoned cart, post-purchase, winback. A/B tests and optimizes on revenue.", art: <ArtEmail /> },
        { role: "Social & Content", title: "Posts. Reels. Iterates.", body: "Creates posts and Reels copy, publishes on schedule, tracks engagement, doubles down on what lands.", art: <ArtCaptions /> },
        { role: "SEO Manager", title: "Collections that rank.", body: "Product and collection SEO, metadata, content briefs, technical fixes. Tracks rankings and ships improvements.", art: <ArtSpark /> },
        { role: "Data Analyst", title: "Numbers that decide.", body: "Pulls cross-platform data, runs attribution, reports weekly, flags what's trending up or breaking down.", art: <ArtKPI items={[
          { l: "Revenue", v: "$18.4k", d: "↑ 12%", dir: "up" },
          { l: "AOV", v: "$72", d: "↑ 4%", dir: "up" },
          { l: "Returns", v: "3.1%", d: "↓ 1%", dir: "up" },
        ]} /> },
      ],
    },
  },
  agency: {
    label: "Marketing agency",
    hint: "Reporting · briefs · QA · triage",
    lead: "Built for how agencies actually deliver, across client retainers, in the tools your team already uses. Start with the trio that protects margin. Add specialists per delivery lane. Review-first by default; earns autonomy on the workflows that have proven themselves.",
    starter: {
      title: "Starter trio",
      price: <React.Fragment>From <b>€1,500/mo</b> · three agents · review-first by default</React.Fragment>,
      cards: [
        { role: "New Business", title: "Pipeline for the agency.", sub: "Outbound · proposals · CRM", body: "Builds target lists, runs outbound to ideal clients, drafts proposals from your templates, keeps the new-business CRM moving. The BD hire from day one.", art: <ArtEmail nodes={[
          { label: "Triggered · ICP agency fit", kind: "start" },
          { label: "Enrich · spend + stack signals", kind: "wait" },
          { label: "Send: opener", kind: "send" },
        ]} /> },
        { role: "Account Ops", title: "Nothing falls through.", sub: "Email · Slack · PM tools", body: "Turns scattered client asks across email, Slack, and project tools into structured tasks, follow-ups, and status updates. Your operations assistant across every account.", art: <ArtMsg text="Routed to Sam · client asks 'can we add a paid section to the report this week?' Added to Wed standup agenda." /> },
        { role: "Reporting", title: "Pulls. Drafts. Flags.", sub: "GA4 · Search Console · ads", body: "Pulls performance data across client tools, drafts the client narrative, flags anomalies. Routes to account managers in Slack before clients see it.", art: <ArtKPI items={[
          { l: "Sessions", v: "42.1k", d: "↑ 14%", dir: "up" },
          { l: "CTR", v: "3.2%", d: "↓ 0.4", dir: "down" },
          { l: "Conv", v: "218", d: "↑ 12", dir: "up" },
        ]} /> },
      ],
    },
    addons: {
      title: "Add specialists per delivery lane",
      price: "Modular · cancel any specialist anytime",
      cards: [
        { role: "Content & Briefs", title: "Strategist-grade briefs.", body: "Keyword clustering, SEO/AEO briefs, content outlines and QA against client SOPs. Strategists edit, not author from scratch.", art: <ArtCaptions items={[
          "Brief · 'best CRM for agencies' · 8 H2s",
          "Cluster · 14 keywords · intent: compare",
          "QA pass · 2 schema issues flagged",
        ]} /> },
        { role: "Performance", title: "Spot. Scale. Pause.", body: "Daily health checks across paid media for every client account. Drafts pause/scale recommendations for the strategist to approve.", art: <ArtSpark /> },
        { role: "QA Crew", title: "Pre-ship checks.", body: "Checks live pages for broken links, metadata, schema, GTM containers, and form submissions before deliverables ship.", art: <ArtStock items={[
          { name: "Schema · /pricing", qty: "Pass", pct: 100, low: false },
          { name: "GTM · /signup", qty: "2 issues", pct: 30, low: true },
        ]} /> },
        { role: "Audit & Insights", title: "Anomalies, surfaced.", body: "Continuous audits across analytics, search, and ad accounts. Surfaces what's worth a client conversation before they ask.", art: <ArtEmail nodes={[
          { label: "Detected · GA4 anomaly", kind: "start" },
          { label: "Diff vs baseline", kind: "wait" },
          { label: "Drafted: client note", kind: "send" },
        ]} /> },
      ],
    },
  },
};

const Crew = () => {
  const [variant, setVariant] = React.useState("startups");
  const v = CREW_VARIANTS[variant];
  return (
    <section className="section sunken" id="crew">
      <div className="wrap">
        <div className="block-head">
          <h2 className="sec-h">Build your crew</h2>
          <p className="sec-lead">
            Pick your business type to see a crew built for it: a starter trio, plus specialists you can add lane by lane. Name each agent whatever your team will actually call it in Slack, or take our defaults. We set them up your way.
          </p>
        </div>

        <div className="crew-switch-row">
          <span className="crew-switch-label">Show crew for</span>
          <div className="crew-switch" role="tablist" aria-label="Crew variant">
            {Object.entries(CREW_VARIANTS).map(([key, def]) => (
              <button
                key={key}
                role="tab"
                aria-selected={variant === key}
                className={"crew-switch-btn" + (variant === key ? " active" : "")}
                onClick={() => setVariant(key)}
              >
                {def.label}
              </button>
            ))}
          </div>
          <span className="crew-switch-hint">{v.hint}</span>
        </div>

        <div className="crew-group">
          <div className="crew-group-head">
            <div className="crew-group-title">{v.starter.title}</div>
            <div className="crew-group-price">{v.starter.price}</div>
          </div>
          <div className="crew-grid">
            {v.starter.cards.map((c) => (
              <CrewCard key={c.role} {...c} />
            ))}
          </div>
        </div>

        <div className="crew-group">
          <div className="crew-group-head">
            <div className="crew-group-title">{v.addons.title}</div>
            <div className="crew-group-price">{v.addons.price}</div>
          </div>
          <div className="crew-grid four">
            {v.addons.cards.map((c) => (
              <CrewCard key={c.role} {...c} />
            ))}
          </div>
        </div>

        <div className="always-on">
          <div className="role-block">
            <div className="role">DevOps · included with every crew</div>
            <h4>So your team never becomes AI infrastructure engineers.</h4>
          </div>
          <p>
            Monitors crew health. Handles API changes, model drift, platform updates. The crew stays up. Your team stays
            focused on the business.
          </p>
          <div className="badge">
            <span className="live-dot" /> Always on
          </div>
        </div>
      </div>
    </section>
  );
};

/* ---------------------- §4 Use cases ---------------------- */

const UCSocial = () => (
  <div className="uc-campaign">
    <div className="uc-camp-head">Content · 1 blog → all platforms</div>
    <div className="uc-camp-row"><span className="uc-tag-a">in</span> LinkedIn · scheduled</div>
    <div className="uc-camp-row"><span className="uc-tag-a">X</span> X · scheduled</div>
    <div className="uc-camp-row"><span className="uc-tag-a">IG</span> Instagram · scheduled</div>
  </div>
);

const UCAlert = () => (
  <div className="uc-alert">
    <div className="uc-alert-head"><span className="uc-dot" /> Audit · anomaly detected</div>
    <div className="uc-alert-row">
      <span>Pixel dedup ratio</span>
      <b className="uc-metric down">51%</b>
    </div>
    <div className="uc-alert-row dim">
      <span>Target</span>
      <b>≥ 95%</b>
    </div>
    <div className="uc-alert-foot">Root cause · duplicate event push · 1 fix queued</div>
  </div>
);

const UCCampaign = () => (
  <div className="uc-campaign">
    <div className="uc-camp-head">Email · Father's Day · 15% off</div>
    <div className="uc-camp-row"><span className="uc-tag-a">A</span> The 15% Father's Day note we sent dad first</div>
    <div className="uc-camp-row"><span className="uc-tag-a">B</span> 48 hours. Father's Day. 15% off.</div>
    <div className="uc-camp-row"><span className="uc-tag-a">C</span> One for him, opens Thursday at 9am</div>
  </div>
);

const UCQuery = () => (
  <div className="uc-query">
    <div className="uc-q-prompt">› what's broken?</div>
    <div className="uc-q-row"><span className="uc-q-name">Email open rate</span><span className="uc-q-val down">↓ 8.4%</span></div>
    <div className="uc-q-row"><span className="uc-q-name">CPM (Meta)</span><span className="uc-q-val down">↑ 22%</span></div>
    <div className="uc-q-row"><span className="uc-q-name">Organic clicks</span><span className="uc-q-val down">↓ 14%</span></div>
  </div>
);

const USE_CASES = [
  {
    tag: "Workflow 01 · Social",
    title: "One blog post, fanned out to every platform.",
    body: "A week of content shipped across 7 platforms with zero human edits: 45 posts in 7 days, each adapted per channel and scheduled.",
    art: <UCSocial />,
  },
  {
    tag: "Workflow 02 · Attribution",
    title: "Audit flagged a 51% Pixel dedup ratio. Target is ≥95%.",
    body: "Root-caused to a duplicate event pushback humans had been missing for months. Recovered attribution. Fixed by Tuesday.",
    art: <UCAlert />,
  },
  {
    tag: "Workflow 03 · Campaign",
    title: "Campaign from one Slack brief.",
    body: "“Father's Day promo, 15% off, send Thurs 9am ET.” 30 seconds later: preview PNG, three subject A/B variants, ready-to-paste HTML.",
    art: <UCCampaign />,
  },
  {
    tag: "Workflow 04 · Marketing pulse",
    title: "“What's broken?”",
    body: "One question, eight seconds: the crew pulls marketing signals from across the stack and flags what needs attention. Say “fix it” and the work fans out across the crew.",
    art: <UCQuery />,
  },
];

const UseCases = () => (
  <section className="section" id="use-cases">
    <div className="wrap">
      <div className="block-head">
        <h2 className="sec-h">Real workflows. Running today</h2>
        <p className="sec-lead">
          Four moves the crew makes every week. The mockups below are live recreations of the actual Slack surfaces.
        </p>
      </div>
      <div className="uc-grid">
        {USE_CASES.map((u, i) => (
          <div className="uc-card" key={i}>
            <div className="uc-tag">{u.tag}</div>
            <h3 className="uc-title">{u.title}</h3>
            <p className="uc-body">{u.body}</p>
            <div className="uc-artifact">{u.art}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ---------------------- §5 Timeline ---------------------- */

const Timeline = () => (
  <section className="section" id="how">
    <div className="wrap">
      <div className="sec-head">
        <div className="sec-num">05 — Timeline</div>
        <div>
          <h2 className="sec-h">Four weeks from discovery to live</h2>
          <p className="sec-lead">
            Not six months. Not "AI in a day." Four weeks, with trust earned per workflow.
          </p>
        </div>
      </div>

      <div className="timeline">
        <div className="week w1">
          <div className="bar" />
          <div className="week-tag">
            <b>Week 01</b> <span className="accent-num">Audit</span>
          </div>
          <h4>We map your business.</h4>
          <p>
            We sit with you, identify your highest-ROI workflows, analyze past emails and tickets to read your voice,
            and lock the crew composition. Pure mapping. No infrastructure yet.
          </p>
          <div className="micro">→ You walk away with a crew design, even if you don't proceed.</div>
        </div>
        <div className="week w2">
          <div className="bar" />
          <div className="week-tag">
            <b>Week 02</b> <span className="accent-num">Build &amp; integrate</span>
          </div>
          <h4>The crew gets built.</h4>
          <p>
            Isolated infrastructure spun up. Integrations connected: Slack, Shopify, Klaviyo, whatever your stack runs
            on. Brand voice loaded. Historical data indexed. Approval routing configured.
          </p>
          <div className="micro">→ The crew exists. Not let out of the basement yet.</div>
        </div>
        <div className="week w3">
          <div className="bar" />
          <div className="week-tag">
            <b>Week 03</b> <span className="accent-num">Soft-launch</span>
          </div>
          <h4>Draft-only mode.</h4>
          <p>
            The crew drafts on historical data. You review every output. We tune voice, tone, edge cases, rules. Daily
            audits in Slack. By end of week, you know exactly what the crew sounds like.
          </p>
          <div className="micro">→ Zero risk. Zero customers see anything.</div>
        </div>
        <div className="week w4">
          <div className="bar" />
          <div className="week-tag">
            <b>Week 04+</b> <span className="accent-num">Live</span>
          </div>
          <h4>Send buttons enabled.</h4>
          <p>
            Tier-1 workflows go live with approvals. Daily pulse fires. Trust expands one channel at a time as
            workflows prove themselves. You stay in control of the pace, indefinitely.
          </p>
          <div className="micro">→ You set the pace. Pull anything back to manual anytime.</div>
        </div>
      </div>
    </div>
  </section>
);

/* ---------------------- Pull quote ---------------------- */

const TESTIMONIALS = [
  {
    id: "startup",
    audience: "Startup",
    quote: "We hired Octocrew before we hired our second marketer. The crew runs the GTM ops I'd otherwise be doing at 11 PM, and the founder hours we got back went straight back into product.",
    who: "Founder & CEO · seed-stage SaaS",
  },
  {
    id: "ecom",
    audience: "E-com",
    quote: "The crew doesn't replace anyone on my team. It makes the four of us feel like fifteen, without the meetings, the management, or the payroll.",
    who: "Founder · 7-figure e-com brand",
  },
  {
    id: "agency",
    audience: "Agency",
    quote: "We took on four new retainers without adding a single hire. Reporting and management don't show up in our hiring plan anymore. They show up in margin.",
    who: "Managing partner · 18-person growth agency",
  },
];

const PullQuote = () => {
  const [i, setI] = React.useState(0);
  const t = TESTIMONIALS[i];
  const go = (n) => setI((n + TESTIMONIALS.length) % TESTIMONIALS.length);
  return (
    <section className="section sunken-deep">
      <div className="wrap">
        <div className="pullquote">
          <div className="pq-label">{window.t(t.audience)}</div>
          <p className="quote" key={t.id}>
            <em>“{window.t(t.quote)}”</em>
          </p>
          <div className="attrib">{window.t(t.who)}</div>
          <div className="pq-nav">
            <button className="pq-arrow" onClick={() => go(i - 1)} aria-label="Previous testimonial">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                <path d="M12 7H2M6 3L2 7l4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <div className="pq-dots" role="tablist">
              {TESTIMONIALS.map((tt, idx) => (
                <button
                  key={tt.id}
                  className={"pq-dot" + (idx === i ? " active" : "")}
                  onClick={() => setI(idx)}
                  aria-label={tt.audience + " testimonial"}
                  role="tab"
                  aria-selected={idx === i}
                />
              ))}
            </div>
            <button className="pq-arrow" onClick={() => go(i + 1)} aria-label="Next testimonial">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { CrewCard, Crew, UseCases, Timeline, PullQuote });
