/* Systemiz site — Interactive Workspace Demo (Notion-style) */
/* Renders a recognizable Notion-flavored workspace: sidebar with department
   toggles + selected sub-pages + a body that swaps when you click around.
   Page templates live in 02d-workspace-pages.jsx and are read off `window`. */

function WorkspaceDemo() {
  // active page id. defaults to the Systemiz OS cockpit.
  const [page, setPage] = React.useState("cockpit");
  // expanded department toggles in the sidebar
  const [open, setOpen] = React.useState({
    strategy: true,
    marketing: false,
    operations: false,
    product: false,
    people: false,
    finance: true
  });

  // tour state — fake cursor that demos clicks when section comes into view
  const frameRef = React.useRef(null);
  const tourStartedRef = React.useRef(false);
  const tourCancelRef = React.useRef(false);
  const [cursor, setCursor] = React.useState({ x: 0, y: 0, visible: false, click: false });

  React.useEffect(() => {
    if (!frameRef.current) return;
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !tourStartedRef.current) {
        tourStartedRef.current = true;
        setTimeout(runTour, 700);
      }
    }, { threshold: 0.4 });
    io.observe(frameRef.current);
    return () => io.disconnect();
  }, []);

  // Cancel the tour the moment the user interacts. Don't fight them.
  React.useEffect(() => {
    const cancel = () => {
      tourCancelRef.current = true;
      setCursor((c) => ({ ...c, visible: false }));
    };
    const frame = frameRef.current;
    if (!frame) return;
    frame.addEventListener("pointerdown", cancel, { once: true });
    return () => frame.removeEventListener("pointerdown", cancel);
  }, []);

  async function runTour() {
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    const TRANS = 1100; // matches css transition for the cursor transform

    const moveTo = async (sel) => {
      if (tourCancelRef.current) return false;
      const frame = frameRef.current;
      if (!frame) return false;
      const el = frame.querySelector(`[data-tour="${sel}"]`);
      if (!el) return false;
      const r = el.getBoundingClientRect();
      const f = frame.getBoundingClientRect();
      setCursor((c) => ({
        ...c,
        x: r.left - f.left + r.width / 2,
        y: r.top - f.top + r.height / 2,
        visible: true,
        click: false
      }));
      // wait the full transition so the cursor actually arrives before clicking
      await sleep(TRANS + 40);
      return !tourCancelRef.current;
    };

    // Click flash. `onClickFire` runs during the ring expansion so any
    // side effects (e.g. expanding a sidebar dept) happen visually IN SYNC
    // with the click rather than after the ring fades.
    const clickFx = async (onClickFire) => {
      if (tourCancelRef.current) return;
      setCursor((c) => ({ ...c, click: true }));
      // small beat so the click ring is visible *first*, then trigger the
      // side effect mid-ring — feels like the click caused it
      await sleep(120);
      if (onClickFire) onClickFire();
      await sleep(360);
      setCursor((c) => ({ ...c, click: false }));
    };

    // Enter from above the frame — cursor glides down past the workspace logo
    // and into the sidebar in one continuous motion.
    const f = frameRef.current.getBoundingClientRect();
    setCursor({ x: f.width * 0.16, y: -60, visible: false, click: false });
    await sleep(40);

    // 1. Click Operations toggle — sidebar expands in sync with the click ring
    if (await moveTo("ops-toggle")) {
      await clickFx(() => setOpen((o) => ({ ...o, operations: true })));
    }
    if (tourCancelRef.current) {setCursor((c) => ({ ...c, visible: false }));return;}

    // 2. Click Company Brain leaf (no page change — visual demo only)
    if (await moveTo("brain-leaf")) await clickFx();
    if (tourCancelRef.current) {setCursor((c) => ({ ...c, visible: false }));return;}

    // 3. Click Chris Punt team card on the right
    if (await moveTo("chris-card")) await clickFx();

    // tour complete — cursor fades out in place
    await sleep(300);
    setCursor((c) => ({ ...c, visible: false }));
  }

  const Icon = window.WSIcon;

  // small Systemiz logo image. used in tabs, sidebar cockpit row
  const Torii = ({ size = 14 }) =>
  <img
    src="assets/systemiz-logo.png"
    alt="Systemiz"
    className="ws-torii-img"
    style={{ width: size, height: size }} />;


  // sidebar tree — updated per Wouter's feedback
  const tree = [
  { id: "strategy", label: "Strategy", color: "#a78bfa", children: [
    { id: "dept_strategy", icon: "target", label: "Strategy Dashboard" },
    { id: "projects_tasks", icon: "kanban", label: "Projects & Tasks" }]
  },
  { id: "marketing", label: "Marketing / Sales", color: "#3b82f6", children: [
    { id: "dept_marketing", icon: "megaphone", label: "Marketing / Sales Dashboard" },
    { id: "crm", icon: "users", label: "CRM" }]
  },
  { id: "operations", label: "Operations", color: "#ef3a4c", children: [
    { id: "dept_operations", icon: "settings-2", label: "Operations Dashboard" },
    { id: "brain", icon: "brain", label: "Company Brain" },
    { id: "kpi", icon: "pie-chart", label: "KPI Dashboard" },
    { id: "claude_os", icon: "bot", label: "Claude OS" },
    { id: "meetings", icon: "video", label: "Meetings" }]
  },
  { id: "people", label: "People / Culture", color: "#ec4899", children: [
    { id: "dept_people", icon: "users", label: "People Dashboard" },
    { id: "hiring", icon: "user-plus", label: "Hiring & Onboarding" },
    { id: "team", icon: "contact", label: "Team Directory" }]
  },
  { id: "finance", label: "Finance / Legal", color: "#22c55e", children: [
    { id: "dept_finance", icon: "wallet", label: "Finance Dashboard" },
    { id: "finance_os", icon: "banknote", label: "Finance OS" },
    { id: "invoices", icon: "receipt", label: "Invoices" }]
  },
  { id: "product", label: "Product / Fulfilment", color: "#fb923c", children: [
    { id: "dept_product", icon: "package", label: "Product Dashboard" }]
  }];


  const titleFor = (id) => {
    if (id === "cockpit") return "Systemiz OS";
    for (const dept of tree) {
      if (id === dept.id || id === "dept_" + dept.id) return dept.label;
      const child = dept.children.find((c) => c.id === id);
      if (child) return child.label;
    }
    if (id === "person_chris") return "Chris Punt";
    if (id === "person_jack") return "Jack Ward";
    return "Workspace";
  };

  // book-a-call CTA — opens the Cal.com audit overlay
  const bookCall = () => {
    if (window.openSystemizAudit) { window.openSystemizAudit(); return; }
    const target = document.getElementById("call") || document.getElementById("booking") || document.getElementById("book") || document.getElementById("contact");
    if (target) {
      window.scrollTo({ top: target.getBoundingClientRect().top + window.scrollY - 60, behavior: "smooth" });
    } else {
      // fallback: jump to bottom of page
      window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
    }
  };

  const Page = window.WorkspacePages && window.WorkspacePages[page];
  const goto = (id) => setPage(id);

  return (
    <section
      className="section workspace-section"
      id="workspace-demo"
      data-screen-label="03b Workspace Demo">
      <div className="shell">
        <div className="section-head reveal">
          <span className="eyebrow">THE NOTION SYSTEM</span>
          <h2>The <span className="accent">workspace</span> your business could run on.</h2>
          <p className="lede">The Notion operating system and single source of truth
for your and your team, organized by department. </p>
        </div>

        <div className="ws-frame reveal" ref={frameRef}>
          {/* fake-cursor tour overlay */}
          <div
            className={"ws-tour-cursor" + (cursor.visible ? " visible" : "") + (cursor.click ? " clicking" : "")}
            style={{ transform: `translate(${cursor.x}px, ${cursor.y}px)` }}
            aria-hidden="true">
            <svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true">
              <path d="M5 3 L5 19 L9.5 14.5 L12 21 L15 19.5 L12.5 13 L19 13 Z" fill="#0a0a0a" stroke="#ffffff" strokeWidth="1.6" strokeLinejoin="round" />
            </svg>
            <span className="ws-tour-ring"></span>
          </div>
          <div className="ws-chrome">
            <div className="ws-traffic">
              <span></span><span></span><span></span>
            </div>
            <div className="ws-tabs">
              <div className="ws-tab active">
                <Torii size={13} /> Systemiz OS
              </div>
            </div>
            <div className="ws-chrome-spacer">
              <span className="ws-chrome-meta">Edited 1m ago</span>
              <button className="ws-share ws-bookcall" onClick={bookCall}>
                Book a call
              </button>
            </div>
          </div>

          <div className="ws-body">
            {/* SIDEBAR */}
            <aside className="ws-sidebar">
              <div className="ws-side-head">
                <div className="ws-side-logo">
                  <img src="assets/notion.png" alt="Notion" className="ws-notion-icon" />
                </div>
                <div className="ws-side-actions">
                  <Icon n="search" />
                  <Icon n="settings-2" />
                </div>
              </div>

              <div className="ws-side-section ws-side-cockpit">
                <div className={"ws-side-row ws-cockpit-row" + (page === "cockpit" ? " active" : "")}
                onClick={() => goto("cockpit")}>
                  <Torii size={14} />
                  <span>Systemiz OS</span>
                </div>
              </div>

              {tree.map((dept) =>
              <div key={dept.id} className="ws-side-section">
                  <div className="ws-side-dept">
                    <button
                    className="ws-dept-toggle"
                    data-tour={dept.id === "operations" ? "ops-toggle" : undefined}
                    onClick={() => setOpen({ ...open, [dept.id]: !open[dept.id] })}
                    aria-label={"toggle " + dept.label}>
                      <Icon n={open[dept.id] ? "chevron-down" : "chevron-right"} />
                    </button>
                    <div
                    className={"ws-dept-label" + (page === "dept_" + dept.id ? " active" : "")}
                    onClick={() => goto("dept_" + dept.id)}
                    style={{ ["--dept-color"]: dept.color }}>
                      <span className="ws-dept-dot" style={{ background: dept.color }}></span>
                      <span className="ws-dept-name">{dept.label}</span>
                    </div>
                  </div>
                  {open[dept.id] &&
                <div className="ws-dept-children">
                      {dept.children.map((c) =>
                  <div
                    key={c.id}
                    data-tour={c.id === "brain" ? "brain-leaf" : undefined}
                    className={"ws-side-leaf" + (page === c.id ? " active" : "")}
                    onClick={() => goto(c.id)}>
                          <Icon n={c.icon} />
                          <span>{c.label}</span>
                        </div>
                  )}
                      <div className="ws-side-leaf ws-side-newpage">
                        <Icon n="plus" />
                        <span>New page</span>
                      </div>
                    </div>
                }
                </div>
              )}
            </aside>

            {/* MAIN PANE */}
            <main className="ws-main">
              {Page ?
              <Page goto={goto} title={titleFor(page)} pageId={page} /> :

              <div className="ws-loading">Loading workspace…</div>
              }
            </main>
          </div>
        </div>

        <div className="ws-hint">
          <Icon n="mouse-pointer-click" />
          <span className="ws-hint-shine">Click the sidebar or any card to explore.</span>
        </div>

        <WorkspaceFeaturesStrip />

        <div className="ws-cta reveal">
          <div className="ws-cta-copy">
            <div className="ws-cta-eyebrow">Like what you see?</div>
            <h3 className="ws-cta-title">Get a Notion AIOS for your business</h3>
            <p className="ws-cta-sub">Book a call and let's map out the exact dashboard, databases and AI automations your team and business needs to scale.</p>
          </div>
          <button className="ws-cta-btn" onClick={bookCall}>
            <span className="ws-cta-btn-label">Book a call</span>
            <Icon n="mouse-pointer-click" />
          </button>
        </div>
      </div>
    </section>);

}

// Marquee strip of "what's inside the system" cards. Two rows scrolling in
// opposite directions. Pause on hover. Cards lifted from the old WhatWeBuild
// section — same content, more dynamic presentation, lives under the dashboard.
function WorkspaceFeaturesStrip() {
  const Icon = window.WSIcon;
  const cards = [
  { ic: "layout-dashboard", title: "CEO Dashboard", tag: "AI weekly summary" },
  { ic: "brain", title: "Business Brain", tag: "Claude context engineering" },
  { ic: "mic", title: "Voice → Task", tag: "Custom Claude Skills" },
  { ic: "trending-up", title: "Automated CRM", tag: "AI lead triage" },
  { ic: "bar-chart-3", title: "Weekly Scorecards", tag: "Live data sync" },
  { ic: "list-checks", title: "Inbox / Capture", tag: "Claude routes it" },
  { ic: "calendar", title: "AI Meeting Notes", tag: "Auto-extraction" },
  { ic: "share-2", title: "MCP Connections", tag: "Claude connections" },
  { ic: "book-open", title: "SOPs & Processes", tag: "Defined for AI" },
  { ic: "users", title: "Team Dashboards", tag: "Role-based" },
  { ic: "user-plus", title: "Onboarding Engine", tag: "Self-serve training" },
  { ic: "kanban", title: "One Source of Truth", tag: "Replaces 10–15 tools" }];

  // split into two rows so they can scroll in opposite directions
  const row1 = cards.slice(0, 6);
  const row2 = cards.slice(6);

  const Card = ({ c }) =>
  <div className="ws-strip-card">
      <span className="ws-strip-ic"><Icon n={c.ic} /></span>
      <div className="ws-strip-card-body">
        <div className="ws-strip-title">{c.title}</div>
        <div className="ws-strip-tag"><span className="ws-strip-dot"></span>{c.tag}</div>
      </div>
    </div>;

  return (
    <div className="ws-strip-wrap reveal">
      <div className="ws-strip-head">
        <span className="eyebrow">Under the hood</span>
        <h3 className="ws-strip-h">What's inside every build.</h3>
      </div>

      <div className="ws-strip">
        <div className="ws-strip-track">
          {[...row1, ...row1].map((c, i) => <Card key={i} c={c} />)}
        </div>
      </div>
      <div className="ws-strip">
        <div className="ws-strip-track reverse">
          {[...row2, ...row2].map((c, i) => <Card key={i} c={c} />)}
        </div>
      </div>
    </div>);

}