/* eslint-disable */
/* =========================================================================
   Helix — Home page
   Hero, scroll-flip pyramid section, content cards, footer (footer is global).
   ========================================================================= */

const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

const HERO_HEADLINES = {
  data_right_way: {
    em: "Helping companies prioritize data."
  },
  ai_starts_data: {
    pre: "Effective AI",
    em: "starts with data."
  },
  before_models: {
    pre: "Before the models,",
    em: "the foundation."
  },
  hype_intelligence: {
    pre: "Less AI hype.",
    em: "More actual intelligence."
  }
};

function HomePage({ onNavigate, onContact, pyramidMode, headlineKey }) {
  const headline = HERO_HEADLINES[headlineKey] || HERO_HEADLINES.data_right_way;

  const scrollToLayer = (layerId) => {
    const idx = LAYERS.findIndex((l) => l.id === layerId);
    if (idx === -1) return;
    const el = document.getElementById("framework");
    if (!el) return;
    const sectionTop = el.offsetTop;
    const sectionScrollable = Math.max(0, el.offsetHeight - window.innerHeight);
    // Land at 40% into each layer's dwell zone so the panel is clearly active
    const fraction = (idx + 0.4) / 5;
    window.scrollTo({ top: sectionTop + sectionScrollable * fraction, behavior: "smooth" });
  };

  return (
    <main className="page-fade">
      <HeroSection headline={headline} pyramidMode={pyramidMode} onContact={onContact} onLayerClick={scrollToLayer} />
      <ScrollExpandSection pyramidMode={pyramidMode} onNavigate={onNavigate} />
      <ContentSection />
    </main>);

}

// ---------------------------------------------------------------------------
// Hero
// ---------------------------------------------------------------------------
function HeroSection({ headline, pyramidMode, onContact, onLayerClick }) {
  return (
    <section className="hero">
      <div className="container hero-inner">
        <h1 className="hero-animate" style={{ animationDelay: "0.05s" }}>
          {headline.pre}<br />
          <em>{headline.em}</em>
        </h1>
        <p className="hero-sub hero-animate" style={{ animationDelay: "0.22s" }}>
          Helix designs and deploys the internal intelligence infrastructure that turns your fragmented operational data into faster, better decisions.
        </p>
        <div className="hero-actions hero-animate" style={{ animationDelay: "0.38s" }}>
          <a className="btn btn-primary" href="#framework">
            See how we work
            <ArrowIcon />
          </a>
          <a className="btn btn-ghost" href="#" onClick={(e) => {e.preventDefault();document.dispatchEvent(new CustomEvent("helix:navigate", { detail: "about" }));}}>
            Meet the team
          </a>
        </div>

        <div className="hero-art hero-animate" style={{ animationDelay: "0.52s" }}>
          <HelixPyramid mode={pyramidMode} orientation="up" revealed={5} labelsInside={true} showLabels={false} interactive={true} onLayerClick={onLayerClick} />
        </div>
      </div>
    </section>);

}

// ---------------------------------------------------------------------------
// Scroll-expand — as the user scrolls, each layer expands to fill the screen,
// building from the BASE up to the apex. Each panel explains how that layer
// helps a client. The pyramid grows bottom-up alongside, active band emphasized.
// ---------------------------------------------------------------------------
const LAYER_BENEFIT = {
  capture: {
    headline: "First, we find every drop of data you own.",
    body: "Before a single dashboard or model, we inventory every system feeding your business — including the ones leadership forgot existed. You can't build on data you can't see.",
    points: ["Full inventory of every source system", "Data profiling & quality scoring", "Historical baselines established"],
    proof: "Identifying how far back usable data goes shapes everything built above it."
  },
  infrastructure: {
    headline: "One environment. One version of the truth.",
    body: "We centralize and connect your sources into a single reliable environment, so every team works from the same numbers — refreshed automatically, available on demand.",
    points: ["Centralized cloud environment (Snowflake / Databricks)", "Automated pipelines & orchestration", "Role-based access control"],
    proof: "Sales, inventory, labor and supplier data, all unified and traceable."
  },
  governance: {
    headline: "Data your CFO can actually trust.",
    body: "We make data trusted, not just available — catalogued, traceable from source to slide, and audit-ready. When two reports disagree, you'll know exactly why.",
    points: ["Data catalog with documented owners", "Source-to-dashboard lineage", "PII policy & audit-ready logs"],
    proof: "Every number traceable back to the raw transaction that produced it."
  },
  intelligence: {
    headline: "Answers without waiting on the analytics team.",
    body: "Clean data becomes role-based dashboards and a shared semantic layer, so your people self-serve the decisions they need instead of filing a request and waiting a week.",
    points: ["Role-based dashboards (Power BI / Tableau)", "Shared semantic layer for one set of definitions", "Self-serve analytics for every team"],
    proof: "The business can answer its own questions without waiting on IT."
  },
  ai: {
    headline: "Now the intelligence becomes predictive.",
    body: "With a solid foundation, AI finally works. Forecasting, automation and models that earn their keep — monitored, retrained, and built to hand off to your team.",
    points: ["Use case identification & prioritization", "Model development & deployment", "Monitoring & continuous retraining"],
    proof: "Models built and trained specifially for your company's own data."
  }
};

function ScrollExpandSection({ pyramidMode, onNavigate }) {
  const sectionRef = useRefH(null);
  const [activeIdx, setActiveIdx] = useStateH(0);

  useEffectH(() => {
    let last = -1;
    const onScroll = () => {
      const el = sectionRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = Math.min(Math.max(-rect.top, 0), total);
      const p = total > 0 ? scrolled / total : 0;
      const idx = Math.min(4, Math.floor(p * 5 + 0.0001));
      if (idx !== last) {last = idx;setActiveIdx(idx);}
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const activeLayer = LAYERS[activeIdx];
  const accent = window.HELIX_RAMP[activeIdx];
  // Flood the whole stage with the active layer's colour (it "expands to cover the section").
  const floodDark = activeIdx <= 2; // dark colours -> light text
  const flood = `linear-gradient(155deg, ${accent} 0%, ${window.mixHex(accent, "#000000", floodDark ? 0.28 : 0.12)} 100%)`;
  const b = LAYER_BENEFIT[activeLayer.id];

  return (
    <section className="scroll-expand" ref={sectionRef} id="framework">
      <div className="scroll-expand-sticky">
        <div className="scroll-expand-pyramid">
          <HelixPyramid
            mode={pyramidMode}
            orientation="up"
            revealed={5}
            active={activeLayer.id}
            emphasizeActive={true}
            labelsInside={true}
            showLabels={false}
            interactive={true}
            onLayerClick={(layerId) => {
              const idx = LAYERS.findIndex(l => l.id === layerId);
              if (idx === -1) return;
              setActiveIdx(idx);
              const el = sectionRef.current;
              if (!el) return;
              const total = el.offsetHeight - window.innerHeight;
              const target = el.offsetTop + (idx / 5) * Math.max(total, 0);
              window.scrollTo({ top: target, behavior: "smooth" });
            }} />
        </div>

        <div className={`scroll-expand-info ${floodDark ? "flood-dark" : "flood-light"}`} style={{ background: flood }}>
          <div className="scroll-expand-panels">
            {LAYERS.map((layer, i) => {
              const lb = LAYER_BENEFIT[layer.id];
              return (
                <div key={layer.id} className={`se-panel ${i === activeIdx ? "is-active" : ""}`}>
                  <div className="se-panel-tag">
                    <span className="se-panel-tag-num">Layer 0{i + 1}</span>
                    <span className="se-panel-tag-name">{layer.label}</span>
                  </div>
                  <h3 className="se-panel-headline">{lb.headline}</h3>
                  <p className="se-panel-body">{lb.body}</p>
                  <ul className="se-panel-points">
                    {lb.points.map((p) => <li key={p}>{p}</li>)}
                  </ul>
                  <div className="se-panel-proof">{lb.proof}</div>
                </div>);
            })}
          </div>
          <div className="scroll-expand-rail" aria-hidden="true">
            {LAYERS.map((layer, i) =>
            <span key={layer.id} className={`se-rail-dot ${i === activeIdx ? "is-active" : ""} ${i < activeIdx ? "is-done" : ""}`} />
            )}
          </div>
        </div>
      </div>
    </section>);

}

// ---------------------------------------------------------------------------
// Content section — live Substack RSS feed, falls back to static placeholders
// ---------------------------------------------------------------------------


const CARD_GRADS = [
"linear-gradient(135deg, #cfe0f2, #f6e6df)",
"linear-gradient(135deg, #1d3f6e, #8aa6c8)",
"linear-gradient(135deg, #3a5d8a, #c9d8ea)"];


function stripHtml(html) {
  const div = document.createElement("div");
  div.innerHTML = html;
  return (div.textContent || div.innerText || "").replace(/\s+/g, " ").trim();
}

function fmtDate(str) {
  try {
    return new Date(str).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  } catch {return str;}
}

function ContentSection() {
  const [items, setItems] = useStateH(null); // null = loading, [] = failed/empty
  const [loaded, setLoaded] = useStateH(false);

  useEffectH(() => {
    const feedUrl = "https://helixstrategies.substack.com/feed";

    function parseXml(xmlText) {
      try {
        const doc = new DOMParser().parseFromString(xmlText, "text/xml");
        const entries = [...doc.querySelectorAll("item")].slice(0, 3);
        if (!entries.length) return null;
        return entries.map((el) => {
          const get = (tag) => el.querySelector(tag)?.textContent?.trim() || "";
          const desc = get("description") || get("content\\:encoded");
          const thumb = el.querySelector("enclosure")?.getAttribute("url") ||
            (desc.match(/src="([^"]+\.(jpg|jpeg|png|webp))"/i) || [])[1] || null;
          return {
            tag: get("category") || "Field note",
            date: fmtDate(get("pubDate")),
            title: get("title"),
            excerpt: stripHtml(desc).slice(0, 180) + "…",
            link: get("link"),
            thumb
          };
        });
      } catch (_) { return null; }
    }

    async function loadFeed() {
      let items = null;

      // 1. rss2json — confirmed working, returns clean JSON
      try {
        const r = await fetch(`https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(feedUrl)}`);
        const d = await r.json();
        if (d.status === "ok" && d.items?.length) {
          items = d.items.slice(0, 3).map((it) => ({
            tag: it.categories?.[0] || "Field note",
            date: fmtDate(it.pubDate),
            title: it.title,
            excerpt: stripHtml(it.description || it.content || "").slice(0, 180) + "…",
            link: it.link,
            thumb: it.thumbnail || null,
          }));
        }
      } catch (_) {}

      // 2. allorigins → XML parse (fallback)
      if (!items) {
        try {
          const r = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(feedUrl)}`);
          const d = await r.json();
          if (d.contents) items = parseXml(d.contents);
        } catch (_) {}
      }

      // 3. corsproxy.io → XML parse (fallback)
      if (!items) {
        try {
          const r = await fetch(`https://corsproxy.io/?${encodeURIComponent(feedUrl)}`);
          const text = await r.text();
          if (text) items = parseXml(text);
        } catch (_) {}
      }

      setItems(items || []);
      setLoaded(true);
    }

    loadFeed();
  }, []);

  const display = loaded ? items || [] : null; // null = still loading

  return (
    <section className="container section-pad" id="writing">
      <div className="content-head reveal">
        <div>
          <h2>Notes from inside the data stack.</h2>
        </div>
        <a href="https://substack.com/@helixstrategies" target="_blank" rel="noreferrer" className="btn btn-ghost">
          View all<ArrowIcon />
        </a>
      </div>

      <div className="swap-zone">
        {/* Loading shimmer */}
        {!loaded &&
        <div style={{ display: "flex", gap: 24 }}>
            {[0, 1, 2].map((i) =>
          <div key={i} style={{ flex: 1, borderRadius: 12, background: "var(--surface)", height: 320, opacity: 0.4 + i * 0.1 }} />
          )}
          </div>
        }

        {/* Single featured post */}
        {loaded && display.length === 1 &&
        <a href={display[0].link} target="_blank" rel="noreferrer" className="post-card post-card--featured reveal">
            <div className="post-card-thumb post-card-thumb--featured"
          style={{ background: CARD_GRADS[0] }}>
              <span className="post-card-cat">{display[0].tag}</span>
            </div>
            <div className="post-card-body post-card-body--featured">
              <h3 className="post-card-title" style={{ fontSize: 22, lineHeight: 1.35 }}>{display[0].title}</h3>
              <p className="post-card-excerpt" style={{ fontSize: 15 }}>{display[0].excerpt}</p>
              <div className="post-card-foot">
                <span>{display[0].date}</span>
                <span className="post-card-dot" />
                <span style={{ opacity: 0.6, fontSize: 13 }}>Read on Substack →</span>
              </div>
            </div>
          </a>
        }

        {/* Multiple posts grid */}
        {loaded && display.length > 1 &&
        <div className="cards-grid">
            {display.map((a, i) =>
          <a key={i} href={a.link} target="_blank" rel="noreferrer" className="post-card">
                <div className="post-card-thumb"
            style={{ background: a.thumb ?
              `url(${a.thumb}) center/cover no-repeat` :
              CARD_GRADS[i % CARD_GRADS.length] }}>
                  <span className="post-card-cat">{a.tag}</span>
                </div>
                <div className="post-card-body">
                  <h3 className="post-card-title">{a.title}</h3>
                  <p className="post-card-excerpt">{a.excerpt}</p>
                  <div className="post-card-foot">
                    <span>{a.date}</span>
                    <span className="post-card-dot" />
                    <span style={{ opacity: 0.6, fontSize: 13 }}>Read on Substack →</span>
                  </div>
                </div>
              </a>
          )}
          </div>
        }

        {/* Feed failed silently — show nothing */}
        {loaded && display.length === 0 && null}
      </div>
    </section>);

}

Object.assign(window, { HomePage, HERO_HEADLINES });