/* global React, ReactDOM */
// YachtingStack — For Yachts page. Outcome-first; cloud/local de-emphasized.
// Full-height snap sections (like home), each anchored for the For Yachts mega-menu.
// Narrative order: what you get (hero) → see it work (agents showcase) →
// what it does for you (flow) → why not a generic chatbot (compare) → what it
// works from (iot) → how it connects (network) → how it lands aboard
// (deployment) → objections (trust) → cta.
// Mega-menu deep-links depend on these section ids: hero, agents, flow, compare,
// iot, network, deployment, trust, cta — keep them when editing.
const { Icon, Eyebrow, Btn, Reveal, DeploymentMap, DeviceShowcase, CompareGrid } = window;

// full-screen snap section — pass `bg` for a section-wide background image, and
// `top` to flow content from just below the nav (for tall sections that would
// otherwise clip when vertically centered).
const Snap = ({ children, id, top = false, style = {}, bg = null, bgOpacity = 0.14 }) => (
  <section id={id} className="snap-sec" style={{ position: "relative", minHeight: "100vh", padding: top ? "110px 32px 84px" : "120px 32px",
    display: "flex", flexDirection: "column", justifyContent: top ? "flex-start" : "center", ...(bg ? { overflow: "hidden" } : null), ...style }}>
    {bg && <div aria-hidden="true" style={{ position: "absolute", inset: 0, backgroundImage: `url(${bg})`, backgroundSize: "cover",
      backgroundRepeat: "no-repeat", backgroundPosition: "center", opacity: bgOpacity, pointerEvents: "none" }} />}
    <div style={{ width: "100%", maxWidth: 1080, margin: "0 auto", position: "relative" }}>{children}</div>
  </section>
);

const Head = ({ children, style = {} }) => (
  <h2 style={{ fontFamily: "var(--font-head)", fontWeight: 400, fontSize: "clamp(28px,3.6vw,44px)", lineHeight: 1.12, color: "var(--ink)", margin: 0, maxWidth: 760, ...style }}>{children}</h2>
);

// The solution showcase — real product screenshots, one device at a time, in the
// shared DeviceShowcase mockups (atoms.jsx): a Desktop/Mobile toggle above the
// laptop / phone, auto-cycling captures from /assets/images/agents/showcase/,
// and a near-fullscreen lightbox over the unscaled originals.
function ShowcaseSection({ d }) {
  return (
    <Snap id="agents" top>
      <Reveal style={{ textAlign: "center", maxWidth: 760, margin: "0 auto" }}>
        <Head style={{ marginTop: 14, marginLeft: "auto", marginRight: "auto", textAlign: "center" }}>Your AI Agents, <span style={{ color: "var(--cyan)" }}>at work</span>.</Head>
        <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-2)", margin: "16px auto 0", maxWidth: 680 }}>
          {d.showcaseBody[0]}<br />{d.showcaseBody[1]}
        </p>
      </Reveal>
      <DeviceShowcase desk={d.showcaseDesk} mob={d.showcaseMob} />
    </Snap>
  );
}

// What is an AI agent? — explainer plus the shared generic-vs-dedicated grid
// (CompareGrid in atoms.jsx, also used by the AI Agents product page).
function CompareSection({ d }) {
  const w = d.whatIs;
  return (
    <Snap id="compare" top>
      <Reveal style={{ maxWidth: 720 }}>
        <Head style={{ marginTop: 14 }}>What is an <span style={{ color: "var(--cyan)" }}>AI agent</span>?</Head>
        <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-2)", margin: "18px 0 0" }}>{w.body}</p>
      </Reveal>
      <Reveal delay={100}>
        <div style={{ maxWidth: 780, margin: "36px auto 0" }}>
          <CompareGrid w={w} />
        </div>
      </Reveal>
    </Snap>
  );
}

// One deployment step (Scope / Install / Sail).
function ProcessStep({ ic, t, desc, i }) {
  return (
    <div style={{ height: "100%", padding: "22px 22px", borderRadius: 16, background: "var(--wa-02)", border: "1px solid var(--hairline)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <span style={{ width: 40, height: 40, borderRadius: 11, background: "rgba(80,134,182,.07)", border: "1px solid rgba(80,134,182,.2)",
          display: "flex", alignItems: "center", justifyContent: "center", color: "var(--cyan-2)" }}><Icon name={ic} size={19} /></span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink-4)" }}>Step {i + 1}</span>
      </div>
      <div style={{ fontFamily: "var(--font-ui)", fontSize: 16, fontWeight: 600, color: "var(--ink)" }}>{t}</div>
      <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-3)", margin: "8px 0 0" }}>{desc}</p>
    </div>
  );
}

// One live-vessel-data feed chip — the card lifts and lightens on hover.
function FeedCard({ ic, t }) {
  const [h, setH] = React.useState(false);
  return (
    <div className="liftcard" onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: "flex", alignItems: "center", gap: 13, padding: "18px 20px", borderRadius: 14,
        background: h ? "var(--wa-07)" : "var(--surface)",
        border: `1px solid ${h ? "rgba(80,134,182,.4)" : "var(--hairline)"}`,
        transition: "transform .3s var(--ease), box-shadow .3s var(--ease), border-color .3s, background .3s" }}>
      <span style={{ width: 40, height: 40, borderRadius: 11, background: h ? "rgba(80,134,182,.16)" : "rgba(80,134,182,.07)", border: "1px solid rgba(80,134,182,.18)",
        display: "flex", alignItems: "center", justifyContent: "center", color: "var(--cyan-2)", flexShrink: 0, transition: "background .3s" }}><Icon name={ic} size={18} /></span>
      <span style={{ fontFamily: "var(--font-ui)", fontSize: 14.5, fontWeight: 500, color: "var(--ink)" }}>{t}</span>
    </div>
  );
}

// FAQ accordion row.
function Faq({ q, a, defaultOpen }) {
  const [open, setOpen] = React.useState(!!defaultOpen);
  return (
    <div style={{ borderBottom: "1px solid var(--hairline)" }}>
      <button onClick={() => setOpen((o) => !o)} aria-expanded={open}
        style={{ all: "unset", cursor: "pointer", display: "flex", width: "100%", boxSizing: "border-box", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "20px 4px" }}>
        <span style={{ fontFamily: "var(--font-ui)", fontSize: 16, fontWeight: 500, color: open ? "var(--ink)" : "var(--ink-2)" }}>{q}</span>
        <Icon name={open ? "Minus" : "Plus"} size={18} color="var(--cyan-2)" />
      </button>
      {open && (
        <p className="ymfade" style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 14.5, lineHeight: 1.7, color: "var(--ink-3)", margin: "0 4px 20px", maxWidth: 680 }}>{a}</p>
      )}
    </div>
  );
}

// Side dot-nav — one dot per full-height section, active one tracked via
// IntersectionObserver, click jumps straight to that section.
const ONBOARD_SECTIONS = [
  { id: "hero", label: "Overview" },
  { id: "agents", label: "See it work" },
  { id: "flow", label: "What it does for you" },
  { id: "compare", label: "What is an agent?" },
  { id: "iot", label: "Live vessel data" },
  { id: "network", label: "AI ecosystem" },
  { id: "deployment", label: "Deployment" },
  { id: "trust", label: "Trust" },
  { id: "cta", label: "Get Started" },
];

function DotNav({ go }) {
  const [active, setActive] = React.useState("hero");
  const [hovered, setHovered] = React.useState(null);

  React.useEffect(() => {
    const els = ONBOARD_SECTIONS.map((s) => document.getElementById(s.id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
    }, { threshold: 0.5 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  const nav = (
    <nav className="onboard-dot-nav" aria-label="Section navigation" style={{ position: "fixed", right: 26, top: "50%",
      transform: "translateY(-50%)", zIndex: 45, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 16 }}>
      {ONBOARD_SECTIONS.map((s) => (
        <div key={s.id} style={{ position: "relative", display: "flex", alignItems: "center" }}
          onMouseEnter={() => setHovered(s.id)} onMouseLeave={() => setHovered(null)}>
          {(hovered === s.id || (active === s.id && hovered === null)) && (
            <span style={{ position: "absolute", right: "calc(100% + 10px)", whiteSpace: "nowrap",
              fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: active === s.id ? 600 : 400,
              color: active === s.id ? "var(--cyan-2)" : "var(--ink-2)", letterSpacing: ".03em",
              textShadow: "0 1px 8px rgba(0,0,0,.85), 0 0 2px rgba(0,0,0,.6)" }}>{s.label}</span>
          )}
          <button onClick={() => go("onboard", s.id)} aria-label={s.label} aria-current={active === s.id ? "true" : undefined}
            style={{ all: "unset", cursor: "pointer", padding: 6, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <span style={{ display: "block", width: active === s.id ? 9 : 6, height: active === s.id ? 9 : 6, borderRadius: "50%",
              background: active === s.id ? "var(--cyan)" : "rgba(255,255,255,.28)",
              boxShadow: active === s.id ? "0 0 10px rgba(80,134,182,.55)" : "none",
              transition: "all .25s var(--ease)" }} />
          </button>
        </div>
      ))}
    </nav>
  );
  // Rendered via portal straight into <body>: the page wrapper's mount/route-change
  // animation sets a transform on it, which turns position:fixed descendants into
  // "fixed relative to that animated ancestor" instead of the viewport — so without
  // this the nav silently scrolls away with the page instead of staying put.
  return ReactDOM.createPortal(nav, document.body);
}

function OnBoard({ go }) {
  const d = window.ONBOARD;
  const feeds = [
    ["Compass", "Navigation & AIS"], ["Gauge", "Engines & propulsion"], ["Droplet", "Tanks & bilge"],
    ["BellRing", "Alarms & safety"], ["Zap", "Power & electrical"], ["Thermometer", "HVAC & climate"],
    ["Wind", "Weather & sea state"], ["Radio", "Comms & connectivity"]];
  return (
    <div style={{ background: "var(--bg)" }}>
      <DotNav go={go} />
      {/* hero — yacht line-art background */}
      <section id="hero" className="snap-sec" style={{ position: "relative", overflow: "hidden", minHeight: "100vh", padding: "128px 32px 72px",
        display: "flex", flexDirection: "column", justifyContent: "center", background: "var(--bg-deep)" }}>
        <div aria-hidden="true" style={{ position: "absolute", inset: 0, backgroundImage: "url(/assets/images/yacht-leaving-port.webp)", backgroundSize: "cover",
          backgroundRepeat: "no-repeat", backgroundPosition: "center right", opacity: 0.05, pointerEvents: "none" }} />
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse 70% 80% at 80% 0%, rgba(80,134,182,.10), transparent 60%)" }} />
        <div aria-hidden="true" style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: "40%", pointerEvents: "none", background: "linear-gradient(to bottom, transparent, var(--bg))" }} />
        <div style={{ width: "100%", maxWidth: 1080, margin: "0 auto", position: "relative" }}>
          <button onClick={() => go("home")} style={{ all: "unset", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 7,
            fontFamily: "var(--font-ui)", fontSize: 13, color: "var(--ink-3)", marginBottom: 26 }}
            onMouseEnter={(e) => e.currentTarget.style.color = "var(--ink)"} onMouseLeave={(e) => e.currentTarget.style.color = "var(--ink-3)"}>
            <Icon name="ArrowLeft" size={15} /> Home
          </button>
          <h1 className="rise" style={{ animationDelay: ".12s", fontFamily: "var(--font-head)", fontWeight: 400,
            fontSize: "clamp(36px,5vw,60px)", lineHeight: 1.06, letterSpacing: "-0.01em", color: "#fff", margin: "16px 0 0", maxWidth: 760 }}>
            <span style={{ color: "var(--cyan)" }}>AI Agents</span>, deployed on board
          </h1>
          <p className="rise" style={{ animationDelay: ".22s", fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: "clamp(16px,1.7vw,19px)",
            lineHeight: 1.65, color: "var(--ink-2)", maxWidth: 620, margin: "22px 0 0" }}>{d.intro}</p>

          <div className="rise" style={{ animationDelay: ".32s", display: "flex", gap: 14, marginTop: 34, flexWrap: "wrap" }}>
            <Btn data-hide-nav-cta="true" size="lg" onClick={() => go("onboarding")} iconRight="ArrowRight">Get On Board</Btn>
          </div>
        </div>

        <div style={{ position: "absolute", bottom: 26, left: "50%", transform: "translateX(-50%)", zIndex: 2 }} className="bob">
          <Icon name="ChevronDown" size={22} color="rgba(255,255,255,.22)" />
        </div>
      </section>

      {/* the solution in action — laptop slideshow of agent deliverables */}
      <ShowcaseSection d={d} />

      {/* what it does for you — outcomes, not plumbing (vertically centered) */}
      <Snap id="flow">
        <Reveal style={{ maxWidth: 700 }}>
          <Head style={{ marginTop: 14 }}>What it does <span style={{ color: "var(--cyan)" }}>for you</span>.</Head>
          <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-2)", margin: "18px 0 0" }}>
            Less chasing, fewer spreadsheets, nothing left to memory. A specialist in every department turns the daily running of the vessel into outcomes you can see.
          </p>
        </Reveal>
        {/* checklist — mirrors the LinkedIn deck's benefits slide */}
        <div className="responsive-grid" style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: "16px 44px", marginTop: 40 }}>
          {d.outcomeChecks.map((t, i) => (
            <Reveal key={t} delay={i * 40}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <span style={{ flexShrink: 0, display: "inline-flex", marginTop: 3 }}><Icon name="Check" size={16} color="var(--good)" /></span>
                <span style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 15.5, lineHeight: 1.55, color: "var(--ink-2)" }}>{t}</span>
              </div>
            </Reveal>
          ))}
        </div>
        <Reveal delay={220}>
          <div style={{ marginTop: 52 }}>
            <div style={{ fontFamily: "var(--font-head)", fontSize: "clamp(21px,2.4vw,28px)", lineHeight: 1.3, color: "var(--ink)" }}>{d.outcomeKicker[0]}</div>
            <div style={{ fontFamily: "var(--font-head)", fontSize: "clamp(21px,2.4vw,28px)", lineHeight: 1.3, color: "var(--cyan-2)", marginTop: 4 }}>{d.outcomeKicker[1]}</div>
          </div>
        </Reveal>
      </Snap>

      {/* what is an AI agent — generic chat vs a dedicated onboard solution */}
      <CompareSection d={d} />

      {/* IoT */}
      <Snap id="iot" bg="/assets/images/sensors.webp" bgOpacity={0.05}>
        <Reveal style={{ maxWidth: 680 }}>
          <Head style={{ marginTop: 14 }}>Get more out of your <span style={{ color: "var(--cyan)" }}>yacht's data</span>.</Head>
          <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16.5, lineHeight: 1.7, color: "var(--ink-2)", margin: "20px 0 0" }}>
            Onboard sensors and systems stream straight to your agents — navigation, engines, tanks, power and alarms — so advice and action are grounded in the vessel's real, current state.
          </p>
        </Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(230px, 1fr))", gap: 14, marginTop: 40 }}>
          {feeds.map(([ic, t], i) => (
            <Reveal key={t} delay={i * 60}>
              <FeedCard ic={ic} t={t} />
            </Reveal>
          ))}
        </div>
      </Snap>

      {/* yacht ⇄ shore network — reuse the exact same diagram as the home page */}
      <DeploymentMap id="network" />

      {/* deployment — cloud, local or both, plus the process */}
      <Snap id="deployment" top>
        <Reveal style={{ maxWidth: 640 }}>
          <Head style={{ marginTop: 14 }}><span style={{ color: "var(--cyan)" }}>Cloud or Local</span> — a bespoke implementation for your yacht.</Head>
          <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16, lineHeight: 1.65, color: "var(--ink-3)", margin: "16px 0 0" }}>
            From the lightest cloud setup to a full local installation, we scope and install around your vessel — new build or refit.
          </p>
        </Reveal>
        <div className="responsive-grid deploy-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40, marginTop: 40, alignItems: "start" }}>
          {d.tiers.map((t, i) => (
            <Reveal key={t.tag} delay={i * 100}>
              <div>
                {/* yacht on top of each tier — illustration only, LOA is not a gate */}
                <div className="deploy-yacht-row" style={{ display: "flex", alignItems: "flex-end", justifyContent: "center", height: 150 }}>
                  <img loading="lazy" decoding="async" src={i === 0 ? "/assets/images/yacht-30m.webp" : "/assets/images/yacht-100m.webp"} alt={t.tag + " deployment"}
                    style={{ width: 380, maxWidth: "100%", height: "auto", filter: "drop-shadow(0 10px 20px rgba(0,0,0,.45))" }} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 22 }}>
                  <Icon name={t.icon} size={17} color="var(--cyan-2)" />
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 16, fontWeight: 600, color: "var(--cyan-2)", letterSpacing: ".02em" }}>{t.tag}</span>
                </div>
                <div style={{ height: 1, background: "var(--hairline)", margin: "14px 0" }} />
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--ink-3)" }}>{t.range}</div>
                <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 14.5, lineHeight: 1.65, color: "var(--ink-2)", margin: "16px 0 0" }}>{t.body}</p>
                <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 16 }}>
                  {t.points.map((p) => (
                    // bullet-style: icon pinned to the first line, text wraps under itself
                    <div key={p} style={{ display: "flex", gap: 9, alignItems: "flex-start" }}>
                      <span style={{ flexShrink: 0, display: "inline-flex", marginTop: 2 }}><Icon name="Check" size={15} color="var(--cyan-2)" /></span>
                      <span style={{ fontFamily: "var(--font-ui)", fontSize: 13, lineHeight: 1.5, color: "var(--ink-2)" }}>{p}</span>
                    </div>
                  ))}
                </div>
              </div>
            </Reveal>
          ))}
        </div>
        <Reveal delay={200}>
          <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 14.5, lineHeight: 1.6, color: "var(--ink-3)", margin: "36px 0 0", textAlign: "center" }}>{d.tiersNote}</p>
        </Reveal>
      </Snap>

      {/* trust & control — FAQ (vertically centered) */}
      <Snap id="trust">
        <Reveal style={{ textAlign: "center", maxWidth: 680, margin: "0 auto" }}>
          <Head style={{ marginTop: 14, marginLeft: "auto", marginRight: "auto", textAlign: "center" }}>You stay <span style={{ color: "var(--cyan)" }}>in command</span>.</Head>
          <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16, lineHeight: 1.7, color: "var(--ink-3)", margin: "16px auto 0", maxWidth: 560 }}>
            Straight answers to what owners and captains ask first.
          </p>
        </Reveal>
        <div style={{ maxWidth: 760, margin: "30px auto 0" }}>
          {d.faq.map(([q, a], i) => <Faq key={i} q={q} a={a} defaultOpen={i === 0} />)}
        </div>
      </Snap>

      {/* CTA — passerelle boarding backdrop, same image as home's "deployed on board" section */}
      <section id="cta" className="snap-sec" style={{ position: "relative", overflow: "hidden", minHeight: "100vh", padding: "120px 32px", textAlign: "center",
        display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <img loading="lazy" decoding="async" src="/assets/images/passarelle-boarding.webp" alt="" aria-hidden="true"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center", opacity: 0.08 }} />
        <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, var(--bg) 0%, transparent 22%, transparent 78%, var(--bg) 100%)" }} />
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse 60% 70% at 50% 50%, rgba(80,134,182,.08), transparent 70%)" }} />
        <Reveal style={{ position: "relative", maxWidth: 600, margin: "0 auto" }}>
          <h2 style={{ fontFamily: "var(--font-head)", fontWeight: 400, fontSize: "clamp(28px,3.6vw,42px)", color: "var(--ink)", margin: 0 }}>
            Multiply your <span style={{ color: "var(--cyan)" }}>crew capabilities</span>,<br />not your headcount.
          </h2>
          <p style={{ fontFamily: "var(--font-ui)", fontWeight: 300, fontSize: 16, lineHeight: 1.7, color: "var(--ink-3)", margin: "18px auto 30px", maxWidth: 460 }}>
            Tell us about your vessel and we'll scope the deployment — specialists, modules and the right mix of cloud and local.
          </p>
          <div style={{ display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
            <Btn data-hide-nav-cta="true" size="lg" onClick={() => go("onboarding")} iconRight="ArrowRight">Get On Board</Btn>
            <Btn variant="ghost" size="lg" onClick={() => go("contact-sales")}>Talk to us</Btn>
          </div>
          <div className="cta-steps" style={{ display: "inline-flex", alignItems: "center", gap: 10, marginTop: 30, flexWrap: "wrap", justifyContent: "center",
            fontFamily: "var(--font-mono)", fontSize: 11.5, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--ink-4)" }}>
            <span>Scope</span><Icon name="ArrowRight" size={13} color="var(--ink-4)" />
            <span>Install</span><Icon name="ArrowRight" size={13} color="var(--ink-4)" />
            <span>Sail</span>
          </div>
        </Reveal>
      </section>
    </div>
  );
}

Object.assign(window, { OnBoard });
