/* global React, ReactDOM, Logo, ArrowRight, FooterCTA, FloatCTA */

/* =====================================================================
   CASE STUDY DETAIL — app-case-detail.jsx
   Data-driven. Renders one case from ?c=<slug>.
   ===================================================================== */

/* ---------------------- Data ---------------------- */

const CASE_DATA = {
  "ecommerce-brand": {
    tag: "Podavach · ecommerce",
    title: "A whole store's marketing, shipped daily",
    sub: "Podavach, a fast-growing ecommerce brand, runs its whole operation, support, store ops, paid, email, social, and content, on a crew of specialist agents, with a single operator approving the work in Slack.",
    stats: [
      { k: "Shipped", n: "~250", l: "support tickets / mo, drafted" },
      { k: "Result", n: "2×", l: "ad tracking accuracy" },
      { k: "Efficiency", n: "$10-15k", l: "monthly hire cost avoided" },
      { k: "Control", n: "1", l: "operator approving the work" },
    ],
    situation:
      "Podavach is a fast-growing ecommerce brand run by a tiny team. A single store still needs the full stack: support across email and social, daily store and inventory ops, paid acquisition, lifecycle email, content, and reporting. Hiring that team would run $10–15k a month and months of ramp the brand did not have.",
    builtLead:
      "A crew of specialist agents covers the whole operation, plugged into Shopify, Klaviyo, Gorgias, and Meta. Support lands as one-tap approval cards in Slack, and most ops run on a schedule.",
    crew: [
      { role: "Customer Support", desc: "Drafts on-brand replies from order and shipping data, posts them as one-tap approval cards, and handles returns and address fixes.", auto: false },
      { role: "E-commerce Ops", desc: "Runs the store end to end: product and inventory sync, preorder toggles, shipping rules, theme updates, and SEO.", auto: true },
      { role: "Ads Manager", desc: "Manages paid to a target ROAS, watches spend daily, and fixed pixel tracking from 51% to over 95% by catching a duplication bug.", auto: true },
      { role: "Email & Lifecycle", desc: "Owns Klaviyo flows and campaigns: nine automated flows driving a large share of repeat revenue.", auto: true },
      { role: "Social & Content", desc: "Plans and drafts the content calendar across platforms and repurposes UGC into posts.", auto: false },
      { role: "Ops Coordinator", desc: "Pulls a daily sales pulse across the whole stack and flags anomalies before they cost money.", auto: true },
    ],
    resultLead: "One operator runs a brand that would otherwise need a full ops-and-marketing team, and the work ships every day.",
    points: [
      "A crew of specialist agents covers support, store ops, paid, email, social, content, and reporting: the work of a full team, shipped every day.",
      "Around 250 support tickets a month drafted on-brand and approved with one tap.",
      "Email runs itself on nine automated flows, a major source of repeat revenue.",
      "Paid tracking accuracy fixed from 51% to over 95% by catching a pixel-duplication bug.",
      "The team they never had to hire would cost $10-15k a month on the market. One person runs it on approvals.",
      "What stayed human: strategy, brand calls, and every customer-facing approval.",
    ],
    quote: {
      text: "I approve the work; the crew runs the store. It's a full ops and marketing team that fits in my Slack.",
      who: "Operator, Podavach",
    },
  },

  "eversolid": {
    tag: "Eversolid · ecommerce",
    title: "The operating capacity of a growth team",
    sub: "Eversolid, an ecommerce brand, runs its store, paid acquisition, content, and day-to-day operations on a four-agent crew, all from one chat, with the owner approving anything that ships. The system is live; the numbers below are its 90-day targets.",
    stats: [
      { k: "Shipped", n: "220", l: "assets produced, target" },
      { k: "Result", n: "+60%", l: "organic sessions, target" },
      { k: "Efficiency", n: "300", l: "hours saved, 90-day target" },
      { k: "Control", n: "0", l: "unapproved risky actions" },
    ],
    timeframe: "90-day targets of the live system. Measured readout in September.",
    situation:
      "Eversolid needed the work that usually falls between several hires: store and inventory ops, paid media, lifecycle email, social and content, attribution, and the upkeep to keep it all running. Staffing each role wasn't realistic, so the brand stood up a four-agent crew instead, each a specialist, coordinating with one another and reporting to a single operator.",
    builtLead:
      "Four specialist agents covering store, ads, content, and operations. They work where the team already does, draft and report on their own, and gate anything that moves money or goes live behind one approval.",
    crew: [
      { role: "Store Ops & SEO", desc: "Runs Shopify and SEO end to end: products, inventory, localization, a 242-keyword semantic core, and storefront audits, reconciled against the order system.", auto: true },
      { role: "Ads Manager", desc: "Watches Meta campaign health, pacing, attribution, and stock fit, and writes creative briefs for the content agent.", auto: true },
      { role: "Content & Email", desc: "Owns Klaviyo email, organic social, and blog, plus the image and video creative for campaigns. Fixed two live abandoned-checkout bugs in its first weeks.", auto: false },
      { role: "Operations", desc: "Keeps the whole system healthy and observable: scheduled reports, diagnostics, and safe maintenance.", auto: true },
    ],
    resultLead: "The crew creates an operating loop: store data feeds content, paid-media insights feed creative, creative learnings feed landing-page fixes, and ops keeps it all reliable. Already shipped below; the rest are its 90-day targets.",
    points: [
      "Already shipped: a 242-keyword semantic core, 174 localization records backfilled, and 2 live abandoned-checkout recovery bugs fixed.",
      "Targeted: 100 to 220 reusable content and creative assets across email, social, blog, and ads.",
      "Targeted: 40 to 80 store, SEO, CRO, and localization improvements shipped or queued for approval.",
      "Targeted: 150 to 300 operator hours saved, and 12 to 30% less avoidable ad waste in reviewed campaigns.",
      "40 to 90 cross-agent handoffs, so store, ads, content, and ops work without the owner relaying every detail.",
      "Zero budget, publish, or credential changes without owner approval.",
      "What stayed human: spend approvals, publishing sign-off, and the calls that touch the brand.",
    ],
    quote: {
      text: "In a quarter it gave us the cadence and output of several part-time specialists, store, paid, content, and ops, without the headcount.",
      who: "Operator, Eversolid",
    },
  },

  "marketing-agency": {
    tag: "Marketing agency · 18 people",
    title: "4 new retainers, zero new hires",
    sub: "An 18-person agency was capacity-locked. Every new client meant more content, social, ads, and email to produce, and the team was already maxed out. We put a crew of specialist agents behind the account team to run the production across client accounts.",
    stats: [
      { k: "Shipped", n: "2×", l: "delivery capacity" },
      { k: "Result", n: "4", l: "new retainers signed" },
      { k: "Efficiency", n: "0", l: "new hires" },
      { k: "Control", n: "100%", l: "ships with strategist sign-off" },
    ],
    situation:
      "The team was good at the work and stuck on the math. Each new retainer added a stack of monthly deliverables, blog posts, social calendars, ad creative, email campaigns, and performance decks, and the agency was at capacity. Strategists were spending their best hours on production instead of strategy and client relationships.",
    builtLead:
      "A crew of specialist agents that runs the marketing production behind the account team, working across every client's stack. Strategists brief and approve; the crew produces.",
    crew: [
      { role: "Content & SEO", desc: "Researches, briefs, writes, and publishes blog and on-page content across client sites, tuned to each brand's voice.", auto: false },
      { role: "Social Media", desc: "Builds and schedules content calendars across every client account and tracks engagement.", auto: false },
      { role: "Ads Manager", desc: "Launches and optimizes paid campaigns across client ad accounts, watches spend, and flags what to change.", auto: true },
      { role: "Email & Lifecycle", desc: "Builds client campaigns and flows, writes and designs them, and ships for approval.", auto: false },
      { role: "Reporting", desc: "Assembles client performance decks on schedule from each account's analytics and ad data.", auto: true },
    ],
    resultLead: "The agency doubled what it could deliver without touching its payroll, and signed four new retainers on the same team.",
    points: [
      "Four new retainers signed and serviced on the existing team.",
      "Delivery capacity roughly doubled across content, social, ads, and email.",
      "About 30 hours a week of production moved off strategists and onto the crew.",
      "Every month the crew produces blog posts, social calendars, ad creative, email campaigns, and performance decks across every retainer.",
      "Margin grew because revenue rose while headcount stayed flat.",
      "What stayed human: strategy, client relationships, and final sign-off on everything that ships.",
    ],
    quote: {
      text: "We stopped turning down work. The crew produces across every account, so our people do the strategy clients actually pay us for.",
      who: "Managing partner, marketing agency",
    },
  },

  "seed-saas": {
    tag: "Seed-stage fintech",
    title: "Work a seed-stage team could never staff",
    sub: "A seed-stage fintech needed a full marketing function across seven platforms: content, community, paid, lifecycle, and weekly reporting. No seed-stage team could hire or afford to run all of it at once. An agent crew ran the whole thing, with one person on strategy and approvals.",
    stats: [
      { k: "Shipped", n: "195", l: "social posts a month, 7 platforms" },
      { k: "Result", n: "7×", l: "organic traffic" },
      { k: "Efficiency", n: "−30%", l: "cost per lead, same budget" },
      { k: "Control", n: "1", l: "person on strategy and approvals" },
    ],
    ledger: [
      "20 blog posts",
      "195 social posts across 7 platforms",
      "4 newsletters",
      "40+ influencers in the outreach funnel",
      "433 Reddit comments",
      "2 ad accounts always live",
    ],
    timeframe: "All within the first 3 months of working together.",
    situation:
      "The team knew exactly what good marketing looked like and had no way to run it at the scale it needed. A full department across seven platforms, daily community presence, paid acquisition, lifecycle email, and stakeholder reporting was simply out of reach on a seed-stage headcount and budget. The realistic choice was to do a fraction of it, or wait months to hire and ramp a team.",
    builtLead:
      "A crew of specialists covering the full marketing mix, with one person setting strategy and approving spend. Most of the work runs on a schedule, unattended.",
    crew: [
      { role: "Social Media", desc: "Ships feature posts and blog fan-outs across seven platforms on a fixed cadence, unattended.", auto: true },
      { role: "Community & Growth", desc: "Runs daily community engagement in two distinct voices, every comment logged with a live link.", auto: true },
      { role: "Ads Manager", desc: "Validates creative cheaply on community channels, scales the winners on paid, reports daily.", auto: false },
      { role: "Email & Lifecycle", desc: "Owns the welcome, winback, and re-engagement journeys end to end.", auto: true },
      { role: "Outreach", desc: "Builds the creator and podcast pipeline and runs partnership outreach.", auto: false },
      { role: "Orchestrator & Reporting", desc: "Routes work across the crew and ships the weekly stakeholder report.", auto: true },
    ],
    resultLead: "The real win was not doing it cheaper. It was doing all of it at all, work a seed-stage team could never have staffed, and the funnel grew while it ran.",
    points: [
      "The biggest win: an entire marketing department's worth of work got done, work that simply was not possible at seed-stage headcount or budget.",
      "Organic traffic grew 7× and referral traffic 10×.",
      "Cost per lead fell 30% cross-channel on the same paid budget.",
      "Reddit alone: 135k post views, 300 organic subreddit followers, and steady traffic from the community.",
      "AI search engines cited the brand 207 times in a single week, naming it on 165 of 240 high-intent queries.",
      "The whole department ran for about the price of one junior hire, always on, no PTO.",
      "What stayed human: strategy, positioning, and spend approvals. One person directed; the crew shipped.",
    ],
    quote: {
      text: "We finally ran the marketing we always knew we needed and could never staff. One person sets the direction, the crew does the work.",
      who: "Operator, seed-stage fintech",
    },
  },
};

const CASE_ORDER = ["seed-saas", "ecommerce-brand", "eversolid", "marketing-agency"];

function getSlug() {
  if (window.__CASE_SLUG__ && CASE_DATA[window.__CASE_SLUG__]) {
    return window.__CASE_SLUG__;
  }
  const params = new URLSearchParams(window.location.search);
  const slug = params.get("c");
  return CASE_DATA[slug] ? slug : CASE_ORDER[0];
}

function setMeta(selector, value, attr = "content") {
  const el = document.querySelector(selector);
  if (el) el.setAttribute(attr, value);
}

function syncCaseSeo(slug, cs) {
  const url = `https://octocrew.ai/case-study-${slug}.html`;
  const title = `${cs.tag} AI Crew Case Study | Octocrew.ai`;
  const description = cs.sub;
  document.title = title;
  setMeta('meta[name="description"]', description);
  setMeta('link[rel="canonical"]', url, "href");
  setMeta('meta[property="og:title"]', title);
  setMeta('meta[property="og:description"]', description);
  setMeta('meta[property="og:url"]', url);
  setMeta('meta[name="twitter:title"]', title);
  setMeta('meta[name="twitter:description"]', description);

  const schema = document.getElementById("case-study-schema");
  if (schema) {
    schema.textContent = JSON.stringify({
      "@context": "https://schema.org",
      "@type": "Article",
      "headline": cs.title,
      "description": description,
      "author": { "@type": "Organization", "name": "Octocrew" },
      "publisher": {
        "@type": "Organization",
        "name": "Octocrew",
        "logo": { "@type": "ImageObject", "url": "https://octocrew.ai/logo.png" }
      },
      "mainEntityOfPage": url
    });
  }
}

/* ---------------------- NavMulti ---------------------- */

const NavMulti = () => {
  const [open, setOpen] = React.useState(false);
  return (
  <nav className="nav">
    <div className="wrap nav-inner">
      <a href="/" className="brand">
        <Logo size={64} />
        <span className="brand-name">
          octocrew<span className="tld">.ai</span>
        </span>
      </a>
      <div className="nav-links">
        <a href="agents.html">{window.t("AI Crew")}</a>
        <a href="case-studies.html">{window.t("Case Studies")}</a>
        <a href="contact.html">{window.t("Contact")}</a>
      </div>
      <LangToggle />
      <a href="contact.html" className="nav-cta" data-octocrew-cal="booking">
        {window.t("Book a discovery call")} <ArrowRight />
      </a>
      <button
        className="nav-burger"
        aria-label="Menu"
        aria-expanded={open}
        onClick={() => setOpen(!open)}
      >
        <span /><span /><span />
      </button>
    </div>
    <div className={"nav-mobile" + (open ? " open" : "")}>
      <div className="wrap">
        <a href="agents.html">{window.t("AI Crew")}</a>
        <a href="case-studies.html">{window.t("Case Studies")}</a>
        <a href="contact.html">{window.t("Contact")}</a>
        <a href="contact.html" className="nav-mobile-cta" data-octocrew-cal="booking">{window.t("Book a discovery call")}</a>
        <LangToggle />
      </div>
    </div>
  </nav>
  );
};

/* ---------------------- Sections ---------------------- */

const DetailHero = ({ cs }) => (
  <section className="hero" id="top">
    <div className="wrap">
      <div style={{ maxWidth: "880px" }}>
        <a className="cs-back" href="case-studies.html">
          <ArrowRight /> {window.t("All case studies")}
        </a>
        <div className="cs-eyebrow">{window.t(cs.tag)}</div>
        <h1 className="h-display">{window.t(cs.title)}</h1>
        <p className="sub">{window.t(cs.sub)}</p>
      </div>
    </div>
  </section>
);

const StatStrip = ({ cs }) => (
  <section className="section sunken">
    <div className="wrap">
      <div className="cs-stats">
        {cs.stats.map((s) => (
          <div className="cs-stat" key={s.l}>
            {s.k && <div className="kind">{window.t(s.k)}</div>}
            <div className="n">{window.t(s.n)}</div>
            <div className="l">{window.t(s.l)}</div>
          </div>
        ))}
      </div>
      {cs.timeframe && (
        <p style={{ textAlign: "center", marginTop: 24, fontSize: 13.5, color: "var(--ink-3)" }}>
          {window.t(cs.timeframe)}
        </p>
      )}
    </div>
  </section>
);

const Situation = ({ cs }) => (
  <section className="section">
    <div className="wrap">
      <div className="cs-narr">
        <h2>{window.t("The situation.")}</h2>
        <p>{window.t(cs.situation)}</p>
      </div>
    </div>
  </section>
);

const WhatWeBuilt = ({ cs }) => (
  <section className="section sunken">
    <div className="wrap">
      <div className="block-head">
        <h2 className="sec-h" dangerouslySetInnerHTML={{ __html: window.t('What we <span class="accent">built</span>') }} />
        <p className="sec-lead">{window.t(cs.builtLead)}</p>
      </div>
      <div className={"crew-grid cs-crew" + (cs.crew.length === 4 ? " four" : "")}>
        {cs.crew.map((c) => (
          <div className="crew-card" key={c.role}>
            <div className="role">{window.t(c.role)}</div>
            <p>{window.t(c.desc)}</p>
            <span className={"cs-auto " + (c.auto ? "on" : "gated")}>
              <span className="dot" />
              {window.t(c.auto ? "Runs autonomously" : "Approval-gated")}
            </span>
          </div>
        ))}
      </div>
      <p className="cs-auto-legend">
        {window.t("Tags mark what already runs on its own versus what still routes through a person for approval. Every workflow starts approval-gated and graduates to autonomous as it earns trust.")}
      </p>
    </div>
  </section>
);

const Ledger = ({ cs }) => {
  if (!cs.ledger) return null;
  return (
    <section className="section sunken-deep" style={{ paddingTop: 48, paddingBottom: 48 }}>
      <div className="wrap">
        <div className="cs-ledger">
          <div className="cs-ledger-head">
            <h3>{window.t("Shipped in a typical month")}</h3>
            <p>{window.t("Output alone is not the value. The value shows in the metrics below. But this is what one month of the crew's work looks like.")}</p>
          </div>
          <ul>
            {cs.ledger.map((item) => (
              <li key={item}>{window.t(item)}</li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
};

const TheResult = ({ cs }) => (
  <section className="section">
    <div className="wrap">
      <div className="cs-narr">
        <h2>{window.t("The result.")}</h2>
        <p>{window.t(cs.resultLead)}</p>
        <ul className="cs-points">
          {cs.points.map((p) => (
            <li key={p}>{window.t(p)}</li>
          ))}
        </ul>
      </div>
    </div>
  </section>
);

const CaseQuote = ({ cs }) => (
  <section
    className="section"
    style={{
      background:
        "radial-gradient(70% 130% at 50% 125%, rgba(63, 0, 127, 0.10), transparent 62%), var(--paper-2)",
      borderTop: "1px solid var(--rule)",
    }}
  >
    <div className="wrap">
      <div className="cs-quote">
        <p className="q">“{window.t(cs.quote.text)}”</p>
        <div className="who">{window.t(cs.quote.who)}</div>
      </div>
    </div>
  </section>
);

/* ---------------------- App ---------------------- */

function App() {
  const slug = getSlug();
  const cs = CASE_DATA[slug];

  React.useEffect(() => {
    syncCaseSeo(slug, cs);
  }, [slug, cs]);

  return (
    <React.Fragment>
      <NavMulti />
      <main id="main-content">
        <DetailHero cs={cs} />
        <StatStrip cs={cs} />
        <Situation cs={cs} />
        <WhatWeBuilt cs={cs} />
        <Ledger cs={cs} />
        <TheResult cs={cs} />
        <CaseQuote cs={cs} />
        <FooterCTA />
      </main>
      <FloatCTA />
    </React.Fragment>
  );
}

Object.assign(window, { NavMulti, DetailHero, StatStrip, WhatWeBuilt, Ledger, TheResult, CaseQuote });

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
