/* global React, ReactDOM */
/* global Logo, ArrowRight, ArrowDown, StackStrip, Crew, UseCases, FooterCTA, FloatCTA */

/* ---------------------- 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" style={{ color: "var(--brand)", fontWeight: 600 }}>{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("Hire your AI crew")} <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("Hire your AI crew")}</a>
        <LangToggle />
      </div>
    </div>
  </nav>
  );
};

/* ---------------------- Hero (agents) ---------------------- */

const AgentsOrbs = ({ cursorRef }) => {
  const limeRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const posRef = React.useRef({ x: 0, y: 0, init: false });

  React.useEffect(() => {
    const el = limeRef.current;
    if (!el) return;
    const container = el.parentNode;
    const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    const restPoint = () => {
      const rect = container.getBoundingClientRect();
      return { x: rect.width * 0.5, y: rect.height * 0.42 };
    };

    const animate = () => {
      const cursor = cursorRef && cursorRef.current;
      const rest = restPoint();
      if (!posRef.current.init) {
        posRef.current.x = rest.x;
        posRef.current.y = rest.y;
        posRef.current.init = true;
      }
      const follow = cursor && cursor.active && !reduceMotion;
      const targetX = follow ? cursor.x : rest.x;
      const targetY = follow ? cursor.y : rest.y;
      const lerp = reduceMotion ? 1 : 0.07;
      posRef.current.x += (targetX - posRef.current.x) * lerp;
      posRef.current.y += (targetY - posRef.current.y) * lerp;
      el.style.transform =
        `translate(${posRef.current.x.toFixed(1)}px, ${posRef.current.y.toFixed(1)}px) translate(-50%, -50%)`;
      rafRef.current = requestAnimationFrame(animate);
    };

    rafRef.current = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(rafRef.current);
  }, [cursorRef]);

  return (
    <div className="hero-orbs" aria-hidden="true">
      <div className="orb orb-ag-1" />
      <div className="orb orb-ag-2" />
      <div className="orb orb-ag-3" />
      <div className="orb orb-ag-cursor" ref={limeRef} />
    </div>
  );
};

const HeroAgents = () => {
  const cursorRef = React.useRef({ x: -9999, y: -9999, active: false });

  const handleMouseMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    cursorRef.current = { x: e.clientX - rect.left, y: e.clientY - rect.top, active: true };
  };
  const handleMouseLeave = () => { cursorRef.current.active = false; };

  return (
    <section
      className="hero hero-agents"
      id="top"
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      style={{ position: "relative", overflow: "hidden" }}
    >
      <AgentsOrbs cursorRef={cursorRef} />
      <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
        <div style={{ maxWidth: 900, margin: "0 auto", textAlign: "center" }}>
          <h1 className="h-display" dangerouslySetInnerHTML={{ __html: window.t('Meet your<br/><span class="accent">marketing crew</span>') }} />
          <p className="sub" style={{ marginLeft: "auto", marginRight: "auto" }}>
            {window.t("A complete marketing team of AI specialists, each running its function end to end. Start with the roles you need most, then scale the crew as you grow.")}
          </p>
          <div className="hero-ctas" style={{ justifyContent: "center" }}>
            <a href="contact.html" className="btn btn-primary" data-octocrew-cal="booking">
              {window.t("Hire your first agent")} <ArrowRight />
            </a>
            <a href="#pricing" className="btn btn-ghost">
              {window.t("See pricing")} <ArrowDown cls="arrow arrow-down" />
            </a>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ---------------------- Crew Roster (full marketing team) ---------------------- */

const AGENT_ROSTER = [
  { name: "Social Media Manager", lead: "Runs your social presence end to end.", bullets: ["Plans the content calendar", "Writes and designs posts", "Publishes across every channel", "Optimizes on engagement, automatically"] },
  { name: "Ads Manager", lead: "Runs paid media end to end.", bullets: ["Builds campaigns and creative", "Launches across platforms", "Watches ROAS in real time", "Reallocates budget on its own"] },
  { name: "Email Marketer", lead: "Owns email and lifecycle end to end.", bullets: ["Builds campaigns and flows", "Writes and designs every send", "Schedules and sends", "A/B tests and optimizes on results"] },
  { name: "SEO Manager", lead: "Runs SEO end to end.", bullets: ["Keyword and content strategy", "Briefs and on-page optimization", "Technical fixes", "Continuous rank tracking"] },
  { name: "Growth Hacker", lead: "Runs growth experiments end to end.", bullets: ["Builds landing pages", "Ships A/B and CRO tests", "Tracks conversion", "Scales what wins"] },
  { name: "Website Manager", lead: "Runs your site end to end.", bullets: ["Builds and updates pages", "Ships fixes around the clock", "Keeps it fast and on-brand", "Tunes for conversion"] },
  { name: "Content Manager", lead: "Owns content end to end.", bullets: ["Content strategy and briefs", "Writing and editing", "Publishing across formats", "Keeps the calendar full"] },
  { name: "Data Analyst", lead: "Runs analytics end to end.", bullets: ["Pulls cross-platform data", "Builds attribution and reporting", "Flags trends and anomalies", "Surfaces what to act on"] },
  { name: "Marketing Operations", lead: "Runs the marketing engine end to end.", bullets: ["Connects your whole stack", "Automates workflows", "Owns reporting", "Keeps the source of truth in sync"] },
];

const CrewRoster = () => (
  <section className="section" id="roster" style={{ position: "relative", overflow: "hidden" }}>
    <div className="aura aura-violet" style={{ width: "60vmin", height: "60vmin", top: "-12%", left: "-8%" }} />
    <div className="aura aura-lime" style={{ width: "52vmin", height: "52vmin", bottom: "-16%", right: "-6%" }} />
    <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
      <div className="block-head">
        <h2 className="sec-h" dangerouslySetInnerHTML={{ __html: window.t('Every role a modern <em class="accent">marketing team</em> needs') }} />
        <p className="sec-lead">
          {window.t("Staff one specialist or the whole team. Each owns a clear function, and on bigger pushes they coordinate, one handing work to the next until the campaign ships.")}
        </p>
      </div>

      <div className="agent-grid">
        {AGENT_ROSTER.map((agent) => (
          <div key={agent.name} className="glass agent-card" style={{
            padding: "clamp(20px, 3vw, 28px)",
          }}>
            <div style={{
              fontFamily: "var(--display)",
              fontSize: 19,
              fontWeight: 600,
              letterSpacing: "-0.01em",
              color: "var(--brand)",
              marginBottom: 10,
            }}>{window.t(agent.name)}</div>
            <p style={{
              fontSize: 16,
              lineHeight: 1.5,
              color: "var(--ink)",
              fontWeight: 600,
              margin: "0 0 14px",
            }}>{window.t(agent.lead)}</p>
            <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 9 }}>
              {agent.bullets.map((b) => (
                <li key={b} style={{
                  position: "relative",
                  paddingLeft: 20,
                  fontSize: 15,
                  lineHeight: 1.5,
                  color: "var(--ink-2)",
                }}>
                  <span className="ac-dot" style={{
                    position: "absolute",
                    left: 0,
                    top: 9,
                    width: 6,
                    height: 6,
                    borderRadius: "50%",
                    background: "var(--brand)",
                  }} />
                  {window.t(b)}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ---------------------- §1 Pricing ---------------------- */

const Pricing = () => (
  <section className="section" id="pricing" style={{ position: "relative", overflow: "hidden" }}>
    <div className="aura aura-violet" style={{ width: "58vmin", height: "58vmin", top: "-14%", right: "-8%" }} />
    <div className="aura aura-lime" style={{ width: "46vmin", height: "46vmin", bottom: "-18%", left: "-6%" }} />
    <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
      <div className="block-head">
        <h2 className="sec-h" dangerouslySetInnerHTML={{ __html: window.t('Plans and <span class="accent">pricing</span>') }} />
        <p className="sec-lead">
          {window.t("Fully operational agents, tailored to your needs, no hidden fees.")}
        </p>
      </div>

      <div className="anchor">
        <div>
          <div className="reframe-anchor first">
            <div className="reframe-label">{window.t("Per agent")}</div>
            <div className="reframe-price">€500<span className="unit">/mo</span></div>
            <div className="reframe-delta">
              {window.t("Billed monthly. Covers 24/7 monitoring, support, updates, and tuning to your data.")}
            </div>
          </div>
          <div className="reframe-anchor">
            <div className="reframe-label">{window.t("Setup")}</div>
            <div className="reframe-price" style={{ fontSize: "clamp(28px, 3.6vw, 42px)" }}><span className="unit">{window.t("From")} </span>€1,500<span className="unit"> {window.t("one-time")}</span></div>
            <div className="reframe-delta">
              {window.t("Per agent: process audit, integration with your stack, rules and historical data loaded, approval cycle configured.")}
            </div>
          </div>
          <a className="micro-cta" href="contact.html">
            {window.t("Hire your first agent")} <ArrowRight />
          </a>
        </div>
        <div>
          <table className="replace-table">
            <thead>
              <tr>
                <th>{window.t("Crew size")}</th>
                <th>{window.t("Setup (one-time)")}</th>
                <th>{window.t("Monthly")}</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["1 agent", "From €1,500", "€500/mo"],
                ["3 agents", "€4,000", "€1,500/mo"],
                ["5 agents", "€6,000", "€2,500/mo"],
              ].map(([size, setup, monthly]) => (
                <tr key={size}>
                  <td>{window.t(size)}</td>
                  <td className="cost">{setup}</td>
                  <td className="rep">{monthly}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <p className="pricing-note">
        {window.t("You bring your own AI model keys, so model usage (tokens) is billed directly by your providers and is not included in the subscription.")}
      </p>
    </div>
  </section>
);

/* ---------------------- §1b Why a crew (cost comparison) ---------------------- */

const COMPARE_ROWS = [
  ["Cost / month", "€1,500+", "€3,000+", "€500"],
  ["Hours covered", "~40 / week", "business hours", "24/7"],
  ["Time to productive", "hiring + weeks of ramp", "onboarding + ramp", "live in 4 weeks"],
  ["When it leaves", "re-hire, re-train", "staff turnover, re-brief", "never quits"],
];

const CompareHire = () => (
  <section className="section sunken" id="compare">
    <div className="wrap">
      <div className="block-head">
        <h2 className="sec-h" dangerouslySetInnerHTML={{ __html: window.t('A specialist\'s job, a <span class="accent">fraction of the cost</span>') }} />
        <p className="sec-lead">
          {window.t("An in-house specialist or an agency spends your budget before the work starts: recruiting, onboarding, retainers, turnover. Each agent is set up once, then runs as long as you need it.")}
        </p>
      </div>

      <div style={{ maxWidth: 860, margin: "0 auto" }}>
        <table className="replace-table">
          <thead>
            <tr>
              <th></th>
              <th>{window.t("A specialist hire")}</th>
              <th>{window.t("A marketing agency")}</th>
              <th>{window.t("An Octocrew agent")}</th>
            </tr>
          </thead>
          <tbody>
            {COMPARE_ROWS.map(([label, specialist, agency, agent]) => (
              <tr key={label}>
                <td>{window.t(label)}</td>
                <td className="cost">{window.t(specialist)}</td>
                <td className="cost">{window.t(agency)}</td>
                <td className="rep">{window.t(agent)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </section>
);

/* ---------------------- §2 The Crew (reuse existing) ---------------------- */
/* Crew component is loaded from components-2.jsx via window global */

/* ---------------------- §3 How Each Agent Works ---------------------- */

const HowAgentWorks = () => (
  <section className="section">
    <div className="wrap">
      <div className="block-head">
        <h2 className="sec-h" dangerouslySetInnerHTML={{ __html: window.t('Every agent follows the same <span class="accent">loop</span>') }} />
        <p className="sec-lead">
          {window.t("No black boxes. You approve every action at first, and each workflow earns its way to automatic. Same loop, every time.")}
        </p>
      </div>

      <div className="scope-grid">
        <div className="scope-item" style={{ gridTemplateColumns: "1fr", gap: 18, minHeight: 280 }}>
          <div>
            <div style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              marginBottom: 16
            }}>
              <span className="x" style={{
                width: 32,
                height: 32,
                fontSize: 14,
                fontWeight: 700,
                background: "var(--brand)",
                color: "#fff",
                border: "none"
              }}>1</span>
              <span style={{
                fontFamily: "var(--mono)",
                fontSize: 12,
                textTransform: "uppercase",
                letterSpacing: "0.08em",
                color: "var(--brand)"
              }}>{window.t("Observes")}</span>
            </div>
            <h5 style={{ fontSize: 20, letterSpacing: "-0.02em", marginBottom: 10 }}>
              {window.t("Reads your connected tools.")}
            </h5>
            <p>
              {window.t("Pulls data from Shopify, Klaviyo, Meta Ads, GA4, Gorgias, your CRM. Aggregates signals across the stack. Detects what changed, what broke, what needs attention.")}
            </p>
          </div>
        </div>
        <div className="scope-item" style={{ gridTemplateColumns: "1fr", gap: 18, minHeight: 280 }}>
          <div>
            <div style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              marginBottom: 16
            }}>
              <span className="x" style={{
                width: 32,
                height: 32,
                fontSize: 14,
                fontWeight: 700,
                background: "var(--brand)",
                color: "#fff",
                border: "none"
              }}>2</span>
              <span style={{
                fontFamily: "var(--mono)",
                fontSize: 12,
                textTransform: "uppercase",
                letterSpacing: "0.08em",
                color: "var(--brand)"
              }}>{window.t("Drafts")}</span>
            </div>
            <h5 style={{ fontSize: 20, letterSpacing: "-0.02em", marginBottom: 10 }}>
              {window.t("Prepares work in your voice.")}
            </h5>
            <p>
              {window.t("Writes ticket replies, campaign briefs, reports, ad recommendations, social captions. Follows your brand rules, your tone, your SOPs. At first, every output waits for you.")}
            </p>
          </div>
        </div>
        <div className="scope-item" style={{ gridTemplateColumns: "1fr", gap: 18, minHeight: 280 }}>
          <div>
            <div style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              marginBottom: 16
            }}>
              <span className="x" style={{
                width: 32,
                height: 32,
                fontSize: 14,
                fontWeight: 700,
                background: "var(--brand)",
                color: "#fff",
                border: "none"
              }}>3</span>
              <span style={{
                fontFamily: "var(--mono)",
                fontSize: 12,
                textTransform: "uppercase",
                letterSpacing: "0.08em",
                color: "var(--brand)"
              }}>{window.t("Acts")}</span>
            </div>
            <h5 style={{ fontSize: 20, letterSpacing: "-0.02em", marginBottom: 10 }}>
              {window.t("Approve at first, automatic once trusted.")}
            </h5>
            <p>
              {window.t("Early on, every action lands as a Slack card with Approve, Edit, and Skip. As a workflow proves itself, you promote it to run on its own. Trust expands one workflow at a time, and you can pull any flow back anytime.")}
            </p>
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* ---------------------- §4 Case Studies ---------------------- */

const CASE_TEASERS = [
  {
    type: "Podavach · ecommerce",
    headline: "Entire online store run by a crew of agents",
    desc: "Support, store ops, paid, email, social, and content, run by a specialist crew with one operator approving the work.",
    href: "case-study-ecommerce-brand.html",
  },
  {
    type: "Seed-stage fintech",
    headline: "Work a seed-stage team could never staff",
    desc: "A full marketing function across seven platforms in the first three months: 7× organic clicks, 207 AI-search citations in a week, paid cost per trial down 31%.",
    href: "case-study-seed-saas.html",
  },
  {
    type: "Eversolid · ecommerce",
    headline: "Store, ads, content, and ops, one crew",
    desc: "A four-agent crew runs the store, paid media, content, and operations from one chat: ~90 hours saved a quarter, 10-20 fixes shipped, 5-15% less ad waste.",
    href: "case-study-eversolid.html",
  },
  {
    type: "Marketing agency · 18 people",
    headline: "4 new retainers without adding headcount",
    desc: "Content, social, ads, email, and reporting produced across every client account, so the team scales without hiring.",
    href: "case-study-marketing-agency.html",
  },
];

const CaseStudies = () => {
  const [i, setI] = React.useState(0);
  const len = CASE_TEASERS.length;
  const visible = [0, 1, 2].map((k) => CASE_TEASERS[(i + k) % len]);
  const prev = () => setI((i - 1 + len) % len);
  const next = () => setI((i + 1) % len);

  return (
    <section className="section sunken-deep" id="cases">
      <div className="wrap">
        <div className="block-head">
          <h2 className="sec-h" dangerouslySetInnerHTML={{ __html: window.t('See the crew <span class="accent">at work</span>') }} />
          <p className="sec-lead">
            {window.t("Real clients running specialist crews today. Here is what changed.")}
          </p>
        </div>

        <div className="case-slider">
          <button className="case-arrow" onClick={prev} aria-label="Previous case studies">‹</button>
          <div className="crew-grid case-slider-track" key={i}>
            {visible.map((cs, k) => (
              <a
                className="crew-card"
                key={cs.type + k}
                href={cs.href}
                style={{ textDecoration: "none", cursor: "pointer" }}
              >
                <div className="role">{window.t(cs.type)}</div>
                <h4 style={{ textWrap: "balance" }}>{window.t(cs.headline)}</h4>
                <p>{window.t(cs.desc)}</p>
                <div style={{
                  marginTop: "auto",
                  paddingTop: 16,
                  fontFamily: "var(--mono)",
                  fontSize: 13,
                  color: "var(--brand)",
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                }}>
                  {window.t("Read case study")} <ArrowRight />
                </div>
              </a>
            ))}
          </div>
          <button className="case-arrow" onClick={next} aria-label="Next case studies">›</button>
        </div>

        <div className="case-dots">
          {CASE_TEASERS.map((_, d) => (
            <button
              key={d}
              className={"case-dot" + (d === i ? " active" : "")}
              onClick={() => setI(d)}
              aria-label={"Go to case study " + (d + 1)}
            />
          ))}
        </div>
      </div>
    </section>
  );
};

/* ---------------------- §5 FAQ (agents-specific) ---------------------- */

const FAQ_AGENTS_ITEMS = [
  {
    q: "How much does it cost?",
    a: "€500 per agent per month, plus one-time setup from €1,500 per agent. The monthly covers 24/7 monitoring, support, updates, and tuning to your data. The setup covers the process audit, integration with your stack, loading your rules and historical data, and configuring the approval cycle.",
  },
  {
    q: "Can I start with one agent and add more?",
    a: "Yes. Hire your first agent, see the numbers, add more when the math works. You can add or remove agents on a monthly basis. No long-term commitments.",
  },
  {
    q: "What does the €500 a month cover?",
    a: "Everything that keeps the agent running and improving: 24/7 monitoring of crew health, API maintenance when platforms change their endpoints, model updates when better models ship, drift handling when Shopify or Klaviyo change their APIs, plus ongoing tuning to your data. Your team never becomes AI infrastructure engineers. It does not cover AI model usage: you bring your own model keys, so tokens are billed directly by your providers.",
  },
  {
    q: "How long until an agent is live?",
    a: "Four weeks from discovery to live. Week 1: audit and crew design. Week 2: build and integrate. Week 3: draft-only mode on historical data. Week 4: live with your approval, then each workflow graduates to running on its own as it earns trust.",
  },
  {
    q: "What if I want to cancel?",
    a: "30-day out clause. We export your full data and logs. No penalties, no lock-in. If it’s not working, we’ll tell you before you tell us.",
  },
  {
    q: "Do agents work 24/7?",
    a: "Yes. Monitoring is continuous: anomalies, stock alerts, and health checks run around the clock. Drafts that need human approval queue in Slack for review during your business hours.",
  },
];

const FAQAgents = () => (
  <section className="section" id="faq">
    <div className="wrap">
      <div className="block-head">
        <h2 className="sec-h">{window.t("Questions we hear on every call")}</h2>
      </div>
      <div className="faq-list">
        {FAQ_AGENTS_ITEMS.map((it, i) => (
          <details className="faq-item" key={i} {...(i === 0 ? { open: true } : {})}>
            <summary>
              <span className="faq-q">{window.t(it.q)}</span>
              <span className="faq-icon" aria-hidden="true">+</span>
            </summary>
            <div className="faq-a">{window.t(it.a)}</div>
          </details>
        ))}
      </div>
    </div>
  </section>
);

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

function AgentsApp() {
  return (
    <React.Fragment>
      <NavMulti />
      <main id="main-content">
        <HeroAgents />
        <CrewRoster />
        <Pricing />
        <CompareHire />
        <HowAgentWorks />
        <CaseStudies />
        <FAQAgents />
        <FooterCTA />
      </main>
      <FloatCTA />
    </React.Fragment>
  );
}

Object.assign(window, { NavMulti, HeroAgents, Pricing, CompareHire, HowAgentWorks, FAQAgents });

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