/* ==========================================================================
   Insights.jsx  —  @role
   Insights research hub (cleanest/most static). Hero + featured anchor article (presenteeism→absenteeism) + article grid (other cards likely placeholder).
   ========================================================================== */
/* PSL Insights Hub — desktop mockup
   Migration target: Webflow (CMS-driven article collection).
   Components introduced here that the dev should rebuild as Webflow classes:
     .i-featured        — featured article tile (Section 02)
     .i-card            — article card (Section 03 grid; designed but hidden at launch)
     .i-form            — single-field email capture (Section 03 empty state)
     .i-empty           — empty-state block shown until CMS has 3+ items
   Reuses .psl-method-style nav, footer, primary/secondary buttons, dark CTA
   section pattern from the existing pages.                                 */

const { useState, useEffect, useRef } = React;

const useInView = (rootMargin = "-10% 0px -10% 0px") => {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current || seen) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }),
      { rootMargin, threshold: 0.05 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [rootMargin, seen]);
  return [ref, seen];
};

/* =====================================================================
   NAV — Insights is footer-only at launch; not in main nav
   ===================================================================== */
const I_Nav = () => {
  const links = [
    { id: "home", label: "Home" },
    { id: "method", label: "Method" },
    { id: "teams", label: "Teams" },
    { id: "individuals", label: "Individuals" },
  ];
  return (
    <nav className="i-nav">
      <div className="i-container i-nav-inner">
        <a href="#" className="i-nav-logo" aria-label="Performance Systems Lab home">
          <img src="assets/logos/PSL-Logo-Header.svg" alt="Performance Systems Lab" />
        </a>
        <div className="i-nav-links">
          {links.map((l) => (
            <a key={l.id} href="#" className="i-nav-link">{l.label}</a>
          ))}
          <a href="#" className="i-nav-cta">Diagnostic</a>
        </div>
      </div>
    </nav>
  );
};

/* =====================================================================
   01 — HERO  (Pattern A · white · 96px)
   ===================================================================== */
const I_Hero = () => {
  const [ref, seen] = useInView("0px");
  return (
    <section className={"i-hero" + (seen ? " is-in" : "")} ref={ref}>
      <div className="i-container">
        <span className="i-overline i-anim-fadeup i-anim-d0">INSIGHTS</span>
        <h1 className="i-hero-h i-anim-fadeup i-anim-d1">
          Thinking on performance under pressure.
        </h1>
        <p className="i-hero-sub i-anim-fadeup i-anim-d2">
          Articles on the structural design of performance — Performance Identity, Execution Architecture, and Sustainable Capacity — drawn from delivery experience, elite-sport principles, and ongoing research.
        </p>
        <p className="i-hero-body i-anim-fadeup i-anim-d3">
          Built for leaders, teams, and individuals who treat consistent performance as an engineering problem rather than a motivational one.
        </p>
        <div className="i-hero-meta i-anim-fadeup i-anim-d4">
          <span>The Insights Hub</span>
          <span className="i-hero-meta-rule" aria-hidden />
          <span>Updated as the methodology research progresses</span>
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   02 — FEATURED ARTICLES  (Pattern B · light grey · 80px)
   Two articles laid out at equal anchor-grade prominence. Each card
   preserves the original metadata + opening-line callout structure.
   ===================================================================== */
const FEATURED_ARTICLES = [
  {
    tag: "SUSTAINABLE CAPACITY",
    date: "9th May 2026",
    read: "8 minutes",
    headline: "Your Key Engineer Just Took Three Days Off. The Reason Should Worry You.",
    sub: "How sustained-pressure delivery environments turn refused recovery into unplanned absence, and what to do about it.",
    quoteEyebrow: "Opening line",
    quote: (
      <>
        Recovery is inevitable.<br />
        The only question is whether it is <em>planned and productive</em>, or <em>unplanned and disruptive</em>.
      </>
    )
  },
  {
    tag: "AI TRANSFORMATION",
    date: "17th May 2026",
    read: "7 minutes",
    headline: "Your AI Transformation Is Hitting Its Adoption Targets. The Team Is Not.",
    sub: "AI did not break your team. The way the transformation has been structured around them did. Most AI transformations fail at the human layer, not the technical one, and the Capacity ring is where the failure surfaces first.",
    quoteEyebrow: "Opening line",
    quote: (
      <>
        AI is not the cause of the failure. <em>The structural design around it is.</em> AI is a <em>load amplifier</em>.
      </>
    )
  }
];

const I_Featured = () => {
  const [ref, seen] = useInView();
  return (
    <section className={"i-featured-section" + (seen ? " is-in" : "")} ref={ref}>
      <style>{`
        .psl-insights .i-featured-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 28px;
        }
        /* When two cards sit side-by-side, the internal left/right split
           gets tight — stack the callout below the metadata column within
           each card so both halves stay legible. */
        .psl-insights .i-featured-grid .i-featured {
          grid-template-columns: 1fr;
        }
        .psl-insights .i-featured-grid .i-featured-left,
        .psl-insights .i-featured-grid .i-featured-right {
          padding: 40px 40px 36px;
        }
        .psl-insights .i-featured-grid .i-featured-left {
          border-right: none;
          border-bottom: 1px solid rgba(13,0,66,0.10);
        }
        .psl-insights .i-featured-grid .i-featured-headline { font-size: 26px; }
        .psl-insights .i-featured-grid .i-featured-quote { font-size: 22px; line-height: 1.35; }
        .psl-insights .i-featured-grid .i-featured-right {
          background:
            linear-gradient(180deg, rgba(25,230,196,0.04) 0%, rgba(25,230,196,0) 80%),
            #FFFCF5;
        }
        @container (max-width: 980px) {
          .psl-insights .i-featured-grid { grid-template-columns: 1fr; }
        }
      `}</style>
      <div className="i-container">
        <div className="i-featured-head">
          <span className="i-featured-head-label">Featured Articles</span>
          <span className="i-featured-head-meta">Latest from the Performance Systems Lab</span>
        </div>

        <div className="i-featured-grid">
          {FEATURED_ARTICLES.map((a, i) => (
            <article key={i} className="i-featured i-anim-fadeup i-anim-d0" style={{ ['--m-i']: i }}>
              <div className="i-featured-left">
                <div className="i-featured-meta">
                  <span className="i-featured-tag">{a.tag}</span>
                  <span className="i-featured-meta-sep" aria-hidden />
                  <span className="i-featured-meta-item">{a.date}</span>
                  <span className="i-featured-meta-sep" aria-hidden />
                  <span className="i-featured-meta-item">{a.read}</span>
                </div>

                <h2 className="i-featured-headline">{a.headline}</h2>

                <p className="i-featured-sub">{a.sub}</p>

                <div className="i-featured-cta-row">
                  <a href="#" className="i-btn i-btn-secondary">
                    <span>Read article</span>
                    <span className="i-btn-arrow" aria-hidden>→</span>
                  </a>
                </div>
              </div>

              <div className="i-featured-right">
                {/* Corner number mark — "N°01 · Featured" sits in the
                    top-right like an editorial annotation. */}
                <span className="i-featured-num" aria-hidden>
                  N<span className="i-featured-num-deg">°</span>{String(i + 1).padStart(2, "0")}
                  <span className="i-featured-num-sep">·</span>
                  <span className="i-featured-num-label">Featured</span>
                </span>

                <div className="i-featured-pull">
                  <p className="i-featured-quote-eyebrow">{a.quoteEyebrow}</p>
                  <p className="i-featured-quote">
                    {/* Hanging open-quote glyph — sits in the margin to
                        the left of the body, like a magazine pull-quote. */}
                    <span className="i-featured-quote-glyph" aria-hidden>“</span>
                    {a.quote}
                  </p>
                  <div className="i-featured-quote-attrib">
                    <span className="i-featured-quote-em" aria-hidden>—</span>
                    <span className="i-featured-quote-attrib-label">From the article</span>
                    <span className="i-featured-quote-attrib-value">Performance Systems Lab</span>
                  </div>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   03 — ARTICLE GRID + EMPTY STATE  (Pattern A · white · 80px)
   At launch the empty state is shown. The article grid below is designed
   but hidden via [data-state="empty"] — Webflow will toggle to "populated"
   once the CMS collection has 3+ items. Toggle button is a designer aid.
   ===================================================================== */

const SAMPLE_ARTICLES = [
  {
    tag: "PERFORMANCE IDENTITY",
    headline: "What Standards Are For (And Why Yours Default Downward).",
    sub: "Standards are a structural layer. Without one, decisions become reactive the moment pressure arrives.",
    date: "12th May 2026",
    read: "7 minutes",
  },
  {
    tag: "EXECUTION ARCHITECTURE",
    headline: "Heroics Are Not A Strategy. They Are A Symptom.",
    sub: "When effort is high but output is inconsistent, the work is being done by people compensating for missing structure.",
    date: "19th May 2026",
    read: "8 minutes",
  },
  {
    tag: "SUSTAINABLE CAPACITY",
    headline: "The Quiet Erosion: Why Performance Drops Without A Visible Failure.",
    sub: "Decision quality declines in increments. Engagement thins. Nobody can point to the moment things broke because nothing broke.",
    date: "26th May 2026",
    read: "11 minutes",
  },
  {
    tag: "PERFORMANCE IDENTITY",
    headline: "How Leadership Alignment Fragments Under Pressure That Exposes It.",
    sub: "Pressure does not create misalignment. It reveals the alignment that was assumed but never built.",
    date: "2nd June 2026",
    read: "6 minutes",
  },
  {
    tag: "EXECUTION ARCHITECTURE",
    headline: "Operating Rhythm: The Cadence That Replaces Reactive Delivery.",
    sub: "A small set of decision rituals, applied consistently, removes the daily renegotiation of how work happens.",
    date: "9th June 2026",
    read: "9 minutes",
  },
  {
    tag: "SUSTAINABLE CAPACITY",
    headline: "Periodisation, Borrowed: What Elite Sport Knows About The Year After The Year.",
    sub: "Champions are built in how the load is structured between rounds, not in the punches themselves.",
    date: "16th June 2026",
    read: "10 minutes",
  },
];

const I_Card = ({ a }) => (
  <a href="#" className="i-card">
    <span className="i-card-tag">{a.tag}</span>
    <h3 className="i-card-headline">{a.headline}</h3>
    <p className="i-card-sub">{a.sub}</p>
    <div className="i-card-foot">
      <span className="i-card-meta">
        <span>{a.date}</span>
        <span className="i-card-meta-dot" aria-hidden />
        <span>{a.read}</span>
      </span>
      <span className="i-card-link">
        Read<span className="i-card-link-arrow" aria-hidden>→</span>
      </span>
    </div>
  </a>
);

const I_GridSection = () => {
  const [state, setState] = useState("empty"); // "empty" | "populated"
  const [ref, seen] = useInView();
  return (
    <section className={"i-grid-section" + (seen ? " is-in" : "")} ref={ref}>
      <div className="i-container">
        <div className="i-grid-wrap" data-state={state}>
          {/* EMPTY STATE — centred, restrained */}
          <div className="i-empty i-anim-fadeup i-anim-d0">
            <span className="i-overline">MORE TO COME</span>
            <p className="i-empty-body">
              More pieces are in development. The library expands as the methodology research progresses.
            </p>
            <div className="i-empty-divider" aria-hidden />
            <p className="i-empty-form-intro">
              Want to be notified when new articles publish? Add your email below.
            </p>
            <form
              className="i-form"
              onSubmit={(e) => { e.preventDefault(); }}
              aria-label="Notify me about new Insights articles"
            >
              <input
                type="email"
                className="i-form-input"
                placeholder="you@yourcompany.com"
                aria-label="Email address"
              />
              <button type="submit" className="i-btn i-btn-primary">Get notified</button>
            </form>
            <p className="i-form-supporting">
              New articles only. No newsletter, no list-sharing, no marketing emails.
            </p>
          </div>

          {/* POPULATED STATE — grid, hidden at launch */}
          <div className="i-grid-head">
            <span className="i-overline">THE LIBRARY</span>
            <span className="i-grid-head-meta">{SAMPLE_ARTICLES.length} articles</span>
          </div>
          <div className="i-grid">
            {SAMPLE_ARTICLES.map((a, i) => <I_Card key={i} a={a} />)}
          </div>
        </div>

        {/* Designer-only toggle to preview both states. Not migrated to Webflow. */}
        <div className="i-state-toggle" role="tablist" aria-label="Preview state">
          <button
            role="tab"
            aria-selected={state === "empty"}
            className={"i-state-btn" + (state === "empty" ? " active" : "")}
            onClick={() => setState("empty")}
          >
            Launch state
          </button>
          <button
            role="tab"
            aria-selected={state === "populated"}
            className={"i-state-btn" + (state === "populated" ? " active" : "")}
            onClick={() => setState("populated")}
          >
            Populated (3+ articles)
          </button>
        </div>
        <p className="i-state-toggle-note">
          Designer preview · Webflow toggles automatically once the CMS has 3+ items
        </p>
      </div>
    </section>
  );
};

/* =====================================================================
   04 — CLOSING CTA  (Pattern C · dark navy · full-bleed)
   ===================================================================== */
const I_ClosingCTA = () => (
  <section className="i-cta">
    <div className="i-container i-cta-inner">
      <h2 className="i-cta-h">Want to apply the thinking?</h2>
      <p className="i-cta-body">
        The PSL Performance Diagnostic is the structured starting point for any leader, team, or individual wanting to understand where their current system stands across the three domains.
      </p>
      <div className="i-cta-row">
        <a href="#" className="i-btn i-btn-primary">
          <span>Take the Performance Diagnostic</span>
          <span className="i-btn-arrow" aria-hidden>→</span>
        </a>
        <a href="#" className="i-btn i-btn-secondary">
          <span>Start a Conversation</span>
          <span className="i-btn-arrow" aria-hidden>→</span>
        </a>
      </div>
    </div>
  </section>
);

/* =====================================================================
   ROOT — footer is the canonical <PSLFooter /> shared across pages
   ===================================================================== */
const Insights = () => {
  // Mount-tick → drives one-shot CSS animations (turquoise bar grow, tag
  // letter-spacing reveal). The intersection-observer animations on
  // sections handle the scroll-triggered fade-ups.
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    const t = requestAnimationFrame(() => setMounted(true));
    return () => cancelAnimationFrame(t);
  }, []);
  return (
    <div
      className={"psl-insights" + (mounted ? " is-mounted" : "")}
      data-screen-label="01 PSL Insights Hub"
    >
      <PSLNav theme="light" active="" />
      <I_Hero />
      <I_Featured />
      <I_GridSection />
      <I_ClosingCTA />
      <PSLFooter />
    </div>
  );
};

Object.assign(window, { Insights });
