/* Systemiz site — Timeline, Fit, Roadmap */

function Timeline({ onBook }) {
  // The 6 layers of an AIOS — Notion holds the bottom three (System, Context, Data);
  // Claude operates the top three (Intelligence, Automation, Optimize).
  // Layers render top-down 1 → 6 to match reading order. Notion logos sit on 1–3, Claude on 4–6.
  const layers = [
  { n: 1, name: "System", tier: "The Foundation", tool: "notion",
    q: "If someone new joined your business tomorrow, could they find everything they need without asking you a single question?" },
  { n: 2, name: "Context", tier: "The Knowledge Layer", tool: "notion",
    q: "If you gave Claude access to your business right now, would it understand your vision and where you're going, how you and your team operates, and the internal processes for running and growing the business?" },
  { n: 3, name: "Data", tier: "The Flow Layer", tool: "notion",
    q: "Do you know your numbers and is your data automated into one dashboard that you can go to for visibility?" },
  { n: 4, name: "Intelligence", tier: "The AI Layer", tool: "claude",
    q: "Can you send a voice note to Claude on your phone and get a full report giving you visibility on what your team is working on and what the numbers for last week was?" },
  { n: 5, name: "Automation", tier: "The Output Layer", tool: "claude",
    q: "Do you have AI running your business and automating tasks in the background without you having to open the chat and ask it to do something for you?" },
  { n: 6, name: "Optimization", tier: "The Hygiene Layer", tool: "claude",
    q: "Will your system improve over time, the longer you use it, without you or your team needing to do anything?" }];


  // answers: { [layerIndex]: 'yes' | 'no' }
  const [answers, setAnswers] = React.useState({});
  const [idx, setIdx] = React.useState(0); // 0..5 = question, 6 = results
  const [revealed, setRevealed] = React.useState(false); // cascade-in trigger
  const stageRef = React.useRef(null);

  // Trigger the cascade animation once when the section scrolls into view
  React.useEffect(() => {
    if (!stageRef.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) {setRevealed(true);io.disconnect();}});
    }, { threshold: 0.18 });
    io.observe(stageRef.current);
    return () => io.disconnect();
  }, []);

  const completed = idx >= layers.length;
  const yesCount = Object.values(answers).filter((a) => a === "yes").length;
  const answeredCount = Object.keys(answers).length;

  // Notion = layers 0–2 (Q1–3), Claude = layers 3–5 (Q4–6)
  const notionYes = [0, 1, 2].filter((i) => answers[i] === "yes").length;
  const claudeYes = [3, 4, 5].filter((i) => answers[i] === "yes").length;
  const tier = (n) => n === 0 ? "none" : n === 3 ? "strong" : "partial";
  const notionTier = tier(notionYes);
  const claudeTier = tier(claudeYes);

  const answer = (val) => {
    const myIdx = idx;
    setAnswers((prev) => ({ ...prev, [myIdx]: val }));
    // Snap colour instantly; just a beat so the user registers the answer.
    setTimeout(() => {setIdx((i) => Math.min(i + 1, layers.length));}, 140);
  };
  const goBack = () => setIdx((i) => Math.max(0, i - 1));
  const reset = () => {setAnswers({});setIdx(0);};

  // 3 × 3 matrix of results (Notion strength × Claude strength)
  const resultMatrix = {
    "none|none": { tag: "Stage 00 · Running on memory", msg: "Your business runs on people (most likely you) instead of systems. The business lives in your head and in 10+ scattered tools. That's where most founders stay stuck. Book a free AIOS strategy call and we'll audit your business and map out the exact system you need to make it visible and scalable." },
    "none|partial": { tag: "Stage 01 · AI on top of nothing", msg: "You're using Claude, but it has no structured backend to act on. Without a system of record, you'll forever just chat with AI and never truly automate your business. Book a free AIOS strategy call and we'll show you exactly what backend to build so Claude can actually automate the boring busy work eating up all your time." },
    "none|strong": { tag: "Stage 01 · AI without a system", msg: "You're using Claude which is great, but with no Notion backend, it can't automate the workflows of your team and truly run autonomously in the background. The leverage comes from the system and putting Claude inside. Book a free AIOS strategy call and we'll map out the Notion system your business and Claude is missing." },
    "partial|none": { tag: "Stage 02 · Foundation, half-built", msg: "You've started organizing your business in Notion and have started to build the foundation. Now it's time to integrate AI and automate your business so you can scale your revenue without scaling your time. Book a free AIOS strategy call and we'll review what you've built and give you the roadmap for automating it with AI." },
    "partial|partial": { tag: "Stage 02 · Two halves, no system", msg: "You've got a little bit of both which is great, but the real leverage of an AIOS comes from the whole being greater than the sum of its parts. Book a free AIOS strategy call and we'll pinpoint exactly which layers you're missing and the order to build them in." },
    "partial|strong": { tag: "Stage 02 · Claude ahead of Notion", msg: "Claude is ahead of your structure, meaning you probably enjoy playing around with Claude more than building systems for your business. The real leverage of Claude is in finishing the Notion backend. Book a free AIOS strategy call and we'll map out how to finish your backend so Claude has something to run on and automate." },
    "strong|none": { tag: "Stage 03 · Notion solid · add intelligence", msg: "Your Notion is in solid shape, now all that's left is integrating Claude and automating your workflows. You're closer than most to a real AIOS. Book a free AIOS strategy call and we'll give you the action plan to layer Claude into your structure and finish your AIOS so you can scale comfortably without working longer hours." },
    "strong|partial": { tag: "Stage 03 · Strong foundation · wire AI", msg: "Congrats on the strong foundation, you're ahead of most people on your AIOS. Book a free AIOS strategy call and we'll pressure-test your systems to find where the biggest unlock in leverage is for your business right now." },
    "strong|strong": { tag: "Stage 04 · You already have an AIOS", msg: "You already operate on a real AIOS, well done! This is where the fun begins. If you want to see what the next level looks like and where the biggest leverage unlock is for your business, book a free AIOS strategy call and let's help you get to the next level." }
  };
  const result = resultMatrix[`${notionTier}|${claudeTier}`];
  const tierMsg = result.msg;
  const tierTag = result.tag;

  const current = !completed ? layers[idx] : null;
  const NotionMark = () => <img src="assets/notion-logo.png" alt="" className="layer-tool-img" />;
  const ClaudeMark = () => <img src="assets/claude-logo.svg" alt="" className="layer-tool-img" />;

  return (
    <section className="section layers-section" id="layers" data-screen-label="06 The 6 Layers">
      <div className="shell">
        <div className="section-head reveal">
          <span className="eyebrow">THE AIOS TEST</span>
          <h2><span className="big-num">6</span> layers. <span className="dim">One operating system.</span></h2>
          <p className="lede">Every successful AIOS is built on these 6 layers. The first 3 is the system, the second 3 is AI. Take the test below to see where yours stands today.

          </p>
        </div>

        <div className="layers-split reveal" ref={stageRef}>
          {/* ============= LEFT: animated stack with side brackets ============= */}
          <div className="layers-visual">
            {/* v23 — Hint pinned to bottom of THIS card via absolute position
                                                                           (see .layers-step-hint CSS). Sits visually below the card and
                                                                           never moves when the right form's height changes. */}
            <div className="phone-step-hint layers-step-hint">
              <i data-lucide="mouse-pointer-click"></i>
              <span>Take the test to see how many you've already built.</span>
            </div>
            <div className="layers-stack-v2">
              {[[0, 3, "notion", NotionMark, "Notion"], [3, 6, "claude", ClaudeMark, "Claude"]].map(([start, end, tool, Mark, label]) =>
              <div className={`layer-group lg-${tool}`} key={tool}>
                  <div className="lg-bars">
                    {layers.slice(start, end).map((l) => {
                    const i = l.n - 1;
                    const ans = answers[i];
                    const state = ans === "yes" ? "yes" : ans === "no" ? "no" : "pending";
                    const active = !completed && idx === i;
                    return (
                      <div
                        key={l.n}
                        className={`layer-bar layer-${l.tool} state-${state}${active ? " active" : ""}${revealed ? " in" : ""}`}
                        style={{ animationDelay: `${i * 90}ms`, transitionDelay: `${i * 50}ms` }}
                        aria-current={active ? "step" : undefined}>
                          <div className="lbar-edge" aria-hidden="true"></div>
                          <div className="lbar-num">{String(l.n).padStart(2, "0")}</div>
                          <div className="lbar-meta">
                            <div className="lbar-name">{l.name}</div>
                            <div className="lbar-tier">{l.tier}</div>
                          </div>
                          <div className="lbar-status">
                            {state === "yes" &&
                          <span className="lbar-ico lbar-ico-yes">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                                  <polyline points="20 6 9 17 4 12" />
                                </svg>
                              </span>
                          }
                            {state === "no" &&
                          <span className="lbar-ico lbar-ico-no">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                                  <line x1="18" y1="6" x2="6" y2="18" />
                                  <line x1="6" y1="6" x2="18" y2="18" />
                                </svg>
                              </span>
                          }
                            {state === "pending" && <span className={`lbar-ico lbar-ico-pending${active ? " active" : ""}`} aria-hidden="true"></span>}
                          </div>
                          <div className="lbar-fill" aria-hidden="true"></div>
                        </div>);
                  })}
                  </div>
                  <div className="lg-bracket" aria-hidden="true">
                    <svg className="lg-curly" viewBox="0 0 40 100" preserveAspectRatio="none">
                      <path className="lg-curly-path"
                    d="M 6 4 C 32 4, 14 38, 36 50 C 14 62, 32 96, 6 96" />
                    </svg>
                    <span className="lg-bracket-mark"><Mark /></span>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* ============= RIGHT: mini quiz ============= */}
          <div className="layers-quiz">
            <div className="lq-head">
              <span className="lq-eyebrow">Take the test</span>
              <h3 className="lq-title">Do you have an <span className="accent">AIOS</span>?</h3>
              <div className="lq-progress" aria-label={`Question ${Math.min(idx + 1, layers.length)} of ${layers.length}`}>
                {layers.map((_, i) => {
                  const ans = answers[i];
                  const cls =
                  ans === "yes" ? "lq-dot yes" :
                  ans === "no" ? "lq-dot no" :
                  i === idx ? "lq-dot current" : "lq-dot";
                  return <span key={i} className={cls} />;
                })}
              </div>
            </div>

            <div className="lq-body">
              {!completed ?
              <>
                  <div className="lq-counter">Question {idx + 1} <span className="sep">·</span> of 6</div>
                  <div className={`lq-layer-pill`}>
                    <span className="lq-layer-num">{String(current.n).padStart(2, "0")}</span>
                    <span className="lq-layer-name">{current.name}</span>
                    <span className="lq-layer-sep">·</span>
                    <span className="lq-layer-tier">{current.tier}</span>
                  </div>
                  <p className="lq-question" key={idx}>{current.q}</p>
                  <div className="lq-buttons">
                    <button className="lq-btn lq-btn-no" onClick={() => answer("no")}>
                      <span className="lq-btn-ico"><i data-lucide="x"></i></span>
                      <span>Not yet</span>
                    </button>
                    <button className="lq-btn lq-btn-yes" onClick={() => answer("yes")}>
                      <span className="lq-btn-ico"><i data-lucide="check"></i></span>
                      <span>Yes</span>
                    </button>
                  </div>
                  {idx > 0 &&
                <button className="lq-back" onClick={goBack} aria-label="Back to previous question">
                      <span aria-hidden="true">←</span>
                    </button>}
                </> :

              <div className="lq-results">
                  <div className="lq-score-wrap">
                    <svg viewBox="0 0 120 120" className="lq-ring" aria-hidden="true">
                      <circle cx="60" cy="60" r="52" className="lq-ring-bg" />
                      <circle cx="60" cy="60" r="52" className="lq-ring-fill"
                    style={{ strokeDasharray: `${yesCount / 6 * 326.7} 326.7` }} />
                    </svg>
                    <div className="lq-score-text">
                      <div className="lq-score-num">{yesCount}<span className="lq-score-out">/6</span></div>
                    </div>
                  </div>
                  <div className="lq-score-breakdown">
                    <span className="lq-score-chip lq-score-chip-notion">
                      <img src="assets/notion-logo.png" alt="" />
                      <span><strong>{notionYes}</strong>/3 Notion</span>
                    </span>
                    <span className="lq-score-chip lq-score-chip-claude">
                      <img src="assets/claude-logo.svg" alt="" />
                      <span><strong>{claudeYes}</strong>/3 Claude</span>
                    </span>
                  </div>
                  <div className="lq-score-tier">{tierTag}</div>
                  <p className="lq-score-msg">{tierMsg}</p>
                  <div className="lq-results-cta">
                    <button className="btn btn-book" onClick={() => window.openSystemizStrategyCall && window.openSystemizStrategyCall()}>
                      Book a free AIOS strategy call
                      <svg className="arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
                    </button>
                    <button className="lq-retry" onClick={reset}>
                      <i data-lucide="rotate-ccw"></i> Take it again
                    </button>
                  </div>
                </div>
              }
            </div>
          </div>
        </div>

      </div>
    </section>);

}

function FitSection({ onBook, ctaCopy = "Join Systemizers" }) {
  const renderFitText = (t) => {
    const m = t.match(/^(.*?) (\([^)]*\))\s*$/);
    if (m) {
      return <>{m[1]} <span style={{ color: "var(--fg-4)" }}>{m[2]}</span></>;
    }
    return t;
  };
  const yes = [
  "You're making real money but you're still the bottleneck, and you can feel the revenue ceiling that creates.",
  "Your business runs on you instead of systems",
  "You want the leverage of a 10-person team without the overhead (you need more leverage, not people)",
  "You think and speak faster than you can document or systemize",
  "You want a simple and intuitive system that can adapt with you as your business grows",
  "You're ready to invest in transformational systems grounded in first principles instead of chasing shiny AI-tools",
  "You understand the importance of speed in today's economy and want a system that allows your business to move fast"];

  const no = [
  "You're pre-revenue or pre-traction (get customers first)",
  "Your business doesn't have any results, numbers or data to automate or systemize yet",
  "You want a cookie-cutter Notion template that will solve all your problems once you duplicate it (systems require work)",
  "You want AI to replace your team, not enhance them (we create AI-powered teams, we don't automate them away)",
  "You're not willing to invest into the systems that makes running and scaling a business possible",
  "You're stuck in corporate approval loops with multiple decision cycles before you can sign off",
  "You expect results with zero involvement from you (even the DFY path requires your input because it's your business)"];

  return (
    <section className="section" id="fit" data-screen-label="08 Who This Is For">
      <div className="shell">
        <div className="section-head reveal">
          <span className="eyebrow">The fit</span>
          <h2>Not for everyone. <span className="dim">Built for the right founder.</span></h2>
          <p className="lede">Hopping on the free AIOS Strategy call is where we figure out which path fits you best. If it's not a fit, we'll point you in the right direction
and give you some free resources.
          </p>
        </div>
        <div className="fit-grid reveal">
          <div className="fit-col yes">
            <h4>This is for you if<span className="badge">Yes</span></h4>
            <ul className="fit-list">
              {yes.map((t, i) =>
              <li key={i}>
                  <span className="mark"><i data-lucide="check"></i></span>
                  <span>{renderFitText(t)}</span>
                </li>
              )}
            </ul>
          </div>
          <div className="fit-col no">
            <h4>This isn't for you if<span className="badge">Not yet</span></h4>
            <ul className="fit-list">
              {no.map((t, i) =>
              <li key={i}>
                  <span className="mark"><i data-lucide="x"></i></span>
                  <span>{renderFitText(t)}</span>
                </li>
              )}
            </ul>
          </div>
        </div>

        {window.CTAPanel && <window.CTAPanel
          eyebrow="Book a call"
          title="Not sure if you're a fit?"
          sub="If you're not sure this is for you and want to talk to someone before deciding, book a free AIOS strategy call. We'll look at your business, answer your questions, and give you a clear roadmap, no pressure if it's not a fit."
          ctaCopy="Book a free AIOS strategy call"
          book={true}
          onBook={onBook} />}
      </div>
    </section>);

}

Object.assign(window, { Timeline, FitSection });