/* Main landing — HuginnDB */
const { useState, useEffect, useMemo, useRef } = React;

/* IntersectionObserver hook — adds 'is-in' class when element enters viewport */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.is-in)");

    // Synchronous first pass: anything already in view at mount gets revealed
    // immediately (the hero, mainly).
    els.forEach((el) => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight && r.bottom > 0) {
        el.classList.add("is-in");
      }
    });

    if (typeof IntersectionObserver === "undefined") {
      els.forEach((el) => el.classList.add("is-in"));
      return;
    }
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("is-in");
            obs.unobserve(e.target);
          }
        });
      },
      { rootMargin: "0px 0px -10% 0px", threshold: 0.08 }
    );
    document.querySelectorAll(".reveal:not(.is-in)").forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);
}

const TWEAK_DEFAULTS = (() => {
  try {
    const raw = document.getElementById("tweak-defaults").textContent;
    return JSON.parse(raw.replace(/\/\*EDITMODE-(BEGIN|END)\*\//g, ""));
  } catch (e) {
    return { accentHue: 240, accentChroma: 0.15, showRunes: true, fontDisplay: "Space Grotesk" };
  }
})();

const GitHubIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.9 1.3 1.9 1.3 1 1.8 2.8 1.3 3.5 1 .1-.8.4-1.3.7-1.6-2.7-.3-5.5-1.3-5.5-6 0-1.3.5-2.4 1.3-3.2-.2-.4-.6-1.6.1-3.2 0 0 1-.3 3.3 1.2a11.5 11.5 0 0 1 6 0C17.3 4.7 18.3 5 18.3 5c.7 1.6.2 2.8.1 3.2.8.8 1.3 1.9 1.3 3.2 0 4.6-2.8 5.6-5.5 5.9.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/>
  </svg>
);

const RuneGlyph = ({ which = 0, size = 28 }) => {
  // 6 different geometric monoline rune-ish glyphs for the why-cards
  const paths = [
    // Eye (mini)
    "M4 14 L14 6 L24 14 L14 22 Z M14 10 L14 18",
    // Crossed daggers
    "M4 4 L24 24 M24 4 L4 24",
    // Vertical with two notches
    "M14 4 L14 24 M14 9 L20 4 M14 19 L20 24",
    // Hexagon with vertical bar
    "M14 4 L24 10 L24 18 L14 24 L4 18 L4 10 Z M14 9 L14 19",
    // Lightning angle
    "M4 4 L18 14 L10 14 L24 24",
    // Concentric diamonds
    "M14 4 L24 14 L14 24 L4 14 Z M14 9 L19 14 L14 19 L9 14 Z",
  ];
  return (
    <svg width={size} height={size} viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square">
      <path d={paths[which % paths.length]} />
    </svg>
  );
};

function useGitHubReleases() {
  const [state, setState] = useState({ releases: [], status: "loading" });
  useEffect(() => {
    fetch("https://api.github.com/repos/Alexfp28/huginnDB/releases", {
      headers: { Accept: "application/vnd.github+json" },
    })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((releases) => setState({ releases, status: "ok" }))
      .catch(() => setState({ releases: [], status: "error" }));
  }, []);
  return state;
}

/* Code block with a copy-to-clipboard button */
function McpCodeBlock({ code, lang, labels }) {
  const [copied, setCopied] = useState(false);
  const flashCopied = () => {
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  const onCopy = () => {
    (navigator.clipboard?.writeText(code) ?? Promise.reject()).then(flashCopied, () => {
      // Clipboard API blocked (permission/context) — fall back to the legacy selection-based copy.
      const ta = document.createElement("textarea");
      ta.value = code;
      ta.style.position = "fixed";
      ta.style.opacity = "0";
      document.body.appendChild(ta);
      ta.select();
      try { document.execCommand("copy"); } catch (e) {}
      document.body.removeChild(ta);
      flashCopied();
    });
  };
  return (
    <div className="mcp-code-wrap">
      <div className="mcp-code-bar">
        <span className="mcp-code-lang">{lang}</span>
        <button className="mcp-copy-btn" onClick={onCopy}>
          {copied ? `✓ ${labels.copied}` : labels.copy}
        </button>
      </div>
      <pre className="mcp-code"><code>{code}</code></pre>
    </div>
  );
}

const Landing = () => {
  const [lang, setLang] = useState(() => localStorage.getItem("hg-lang") || "es");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [activeMcpClient, setActiveMcpClient] = useState(0);
  const { releases } = useGitHubReleases();

  useEffect(() => {
    localStorage.setItem("hg-lang", lang);
  }, [lang]);

  // Apply tweaks to CSS vars
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", `oklch(0.72 ${tweaks.accentChroma} ${tweaks.accentHue})`);
    root.style.setProperty("--accent-2", `oklch(0.78 ${Math.max(tweaks.accentChroma - 0.03, 0)} ${tweaks.accentHue - 5})`);
    root.style.setProperty("--accent-dim", `oklch(0.45 ${Math.max(tweaks.accentChroma - 0.05, 0)} ${tweaks.accentHue + 5})`);
  }, [tweaks.accentHue, tweaks.accentChroma]);

  const t = COPY[lang];
  useReveal();

  return (
    <React.Fragment>
      {/* ─── NAV ───────────────────────── */}
      <nav className="top">
        <div className="wrap">
          <div className="nav-row">
            <div className="brand">
              <span className="brand-mark" style={{ color: "var(--accent)" }}>
                <HuginnMark size={28} stroke={1.5} withFrame={true} />
              </span>
              <span className="brand-name">HuginnDB</span>
            </div>

            <div className="nav-links">
              <a href="#preview">{t.nav.mockup}</a>
              <a href="#why">{t.nav.features}</a>
              <a href="#mcp">{t.nav.mcp}</a>
              <a href={t.compare.href}>{t.nav.compare}</a>
              <a href="https://github.com/Alexfp28/huginnDB#readme" target="_blank" rel="noreferrer">{t.nav.docs}</a>
            </div>

            <div className="nav-cta">
              <div className="lang-toggle" role="group" aria-label="Language">
                <button className={lang === "es" ? "active" : ""} onClick={() => setLang("es")}>ES</button>
                <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
              </div>
              <a className="btn btn-ghost" href="https://github.com/Alexfp28/huginnDB" target="_blank" rel="noreferrer">
                <GitHubIcon size={14} /> GitHub
              </a>
            </div>
          </div>
        </div>
      </nav>

      {/* ─── HERO ──────────────────────── */}
      <section className="hero">
        <div className="wrap">
          <div className="hero-logo-wrap reveal">
            <span className="hero-logo huginn-glow-pulse" style={{ color: "var(--accent)" }}>
              <HuginnMark size={160} stroke={1.4} withFrame={true} withRunes={true} animated={true} />
            </span>
          </div>

          <div className="hero-eyebrow reveal delay-1">{t.hero.eyebrow}</div>

          <h1 className="reveal delay-2">
            {t.hero.title_a} <em>{t.hero.title_b}</em>
          </h1>

          <p className="lede reveal delay-3">{t.hero.lede}</p>

          <div className="hero-ctas reveal delay-4">
            <a className="btn btn-primary btn-large" href={releases[0]?.html_url || "https://github.com/Alexfp28/huginnDB/releases"} target="_blank" rel="noreferrer">
              ↓ {t.hero.cta_download}
              {releases[0] && <span className="hero-version-badge">{releases[0].tag_name}</span>}
            </a>
            <a className="btn btn-ghost btn-large" href="https://github.com/Alexfp28/huginnDB" target="_blank" rel="noreferrer">
              <GitHubIcon size={14} /> {t.hero.cta_github}
            </a>
          </div>

          <div className="hero-meta reveal delay-5">
            <span><span className="dot pulse-dot"></span> {releases[0] ? releases[0].tag_name + " · " + (releases[0].prerelease ? "pre-release" : "stable") : t.hero.meta_alpha}</span>
            <span>{t.hero.meta_platforms}</span>
            <span>{t.hero.meta_license}</span>
          </div>
        </div>
      </section>

      {/* ─── MOCKUP ────────────────────── */}
      <section id="preview" className="mockup-section">
        <div className="wrap">
          <div className="section-head reveal">
            <div className="section-tag">{t.mockup.tag}</div>
            <h2 className="section-title">{t.mockup.title}</h2>
            <p className="section-sub">{t.mockup.sub}</p>
          </div>
          <div className="mockup-wrap reveal delay-1">
            <HuginnMockup />
          </div>
        </div>
      </section>

      {/* ─── COMPARE TEASER ────────────── */}
      <section className="compare-teaser">
        <div className="wrap">
          <div className="ct-row reveal">
            <div className="ct-copy">
              <div className="ct-eyebrow">{t.compare.eyebrow}</div>
              <p className="ct-line">
                {t.compare.line} <a className="ct-link" href={t.compare.href}>{t.compare.cta} →</a>
              </p>
            </div>
            <div className="cmp-chip-row">
              {t.compare.tools.map((name, i) => (
                <span className={"cmp-chip" + (i === 0 ? " on" : "")} key={name}>
                  <span className={"cmp-dot" + (i === 0 ? " on" : "")}></span>{name}
                </span>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* ─── WHY HUGINN ────────────────── */}
      <section id="why" className="why-section">
        <div className="wrap">
          <div className="section-head reveal">
            <div className="section-tag">{t.why.tag}</div>
            <h2 className="section-title">{t.why.title}</h2>
            <p className="section-sub">{t.why.sub}</p>
          </div>

          <div className="why-grid">
            {t.why.cards.map((c, i) => (
              <div className={`why-card reveal delay-${(i % 6) + 1}`} key={i}>
                <div className="why-card-num">/ {c.n}</div>
                <h3>{c.t}</h3>
                <p>{c.b}</p>
                <span className="glyph"><RuneGlyph which={i} /></span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ─── MCP CONNECTOR ─────────────── */}
      <section id="mcp" className="mcp-section">
        <div className="wrap">
          <div className="section-head reveal">
            <div className="section-tag">{t.mcp.tag}</div>
            <h2 className="section-title">{t.mcp.title}</h2>
            <p className="section-sub">{t.mcp.sub}</p>
          </div>

          <p className="mcp-panel-note reveal">{t.mcp.panel_note}</p>

          <div className="mcp-policies reveal delay-1">
            <div className="mcp-policies-head">{t.mcp.policies_title}</div>
            <div className="mcp-policy-grid">
              {t.mcp.policies.map((p, i) => (
                <div className={`mcp-policy-card tone-${p.tone}`} key={i}>
                  <div className="mcp-policy-name">{p.t}</div>
                  <p>{p.d}</p>
                </div>
              ))}
            </div>
            <p className="mcp-policies-note">{t.mcp.policies_note}</p>
          </div>

          <div className="mcp-clients reveal delay-2">
            <div className="mcp-clients-head">{t.mcp.clients_title}</div>
            <div className="mcp-tabs" role="tablist">
              {t.mcp.clients.map((c, i) => (
                <button
                  key={c.id}
                  role="tab"
                  aria-selected={activeMcpClient === i}
                  className={"mcp-tab" + (activeMcpClient === i ? " active" : "")}
                  onClick={() => setActiveMcpClient(i)}
                >
                  {c.label}
                </button>
              ))}
            </div>

            {(() => {
              const c = t.mcp.clients[activeMcpClient];
              return (
                <div className="mcp-tab-panel">
                  <McpCodeBlock code={c.code} lang={c.lang} labels={{ copy: t.mcp.copy, copied: t.mcp.copied }} />
                  {c.caption && <p className="mcp-caption">{c.caption}</p>}
                  {c.code2 && <McpCodeBlock code={c.code2} lang={c.code2lang} labels={{ copy: t.mcp.copy, copied: t.mcp.copied }} />}
                </div>
              );
            })()}
          </div>

          <div className="mcp-tools reveal delay-3">
            <div className="mcp-tools-head">{t.mcp.tools_title}</div>
            <div className="mcp-tools-grid">
              {t.mcp.tools.map((tool, i) => (
                <div className="mcp-tool" key={i}>
                  <code>{tool.t}</code>
                  <p>{tool.d}</p>
                </div>
              ))}
            </div>
          </div>

          <div className="mcp-cta reveal">
            <a href="https://github.com/Alexfp28/huginnDB/blob/main/docs/MCP.md" target="_blank" rel="noreferrer">
              {t.mcp.cta} →
            </a>
          </div>
        </div>
      </section>

      {/* ─── ABOUT ─────────────────────── */}
      <section className="about-section">
        <div className="wrap">
          <div className="dev-card reveal">
            <div className="dev-avatar">A</div>
            <div className="dev-text">
              <small>{t.dev.kicker}</small>
              <div style={{ marginTop: 4 }}><strong>{t.dev.name}</strong></div>
              <p>{t.dev.body}</p>
            </div>
            <a className="btn btn-ghost" href="https://shion.es" target="_blank" rel="noreferrer">
              shion.es ↗
            </a>
          </div>
        </div>
      </section>

      {/* ─── FOOTER ────────────────────── */}
      <footer>
        <div className="wrap">
          <div className="footer-grid">
            <div className="footer-brand">
              <div className="brand">
                <span className="brand-mark" style={{ color: "var(--accent)" }}>
                  <HuginnMark size={28} stroke={1.5} withFrame={true} />
                </span>
                <span className="brand-name">HuginnDB</span>
              </div>
              <p>{t.footer.blurb}</p>
              <p style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-dim)", marginTop: 16, letterSpacing: "0.02em" }}>
                ⤬ {t.footer.tagline}
              </p>
            </div>
            {t.footer.cols.map((col, i) => (
              <div className="footer-col" key={i}>
                <h5>{col.h}</h5>
                <ul>
                  {col.links.map(([label, href], j) => (
                    <li key={j}>
                      <a href={href} target={href.startsWith("http") ? "_blank" : undefined} rel="noreferrer">{label}</a>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
          <div className="footer-bottom">
            <span>{t.footer.legal}</span>
            <span>github.com/Alexfp28/huginnDB</span>
          </div>
        </div>
      </footer>

      {/* ─── TWEAKS PANEL ──────────────── */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent">
          <TweakSlider label="Hue" value={tweaks.accentHue} min={0} max={360} step={1}
            onChange={(v) => setTweak("accentHue", v)} />
          <TweakSlider label="Chroma" value={tweaks.accentChroma} min={0} max={0.25} step={0.005}
            onChange={(v) => setTweak("accentChroma", v)} />
        </TweakSection>
        <TweakSection label="Quick presets">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
            {[
              ["Ice", 240, 0.15],
              ["Hawk", 75, 0.16],
              ["Blood", 25, 0.16],
              ["Phos", 145, 0.16],
            ].map(([name, h, c]) => (
              <button
                key={name}
                onClick={() => { setTweak("accentHue", h); setTweak("accentChroma", c); }}
                style={{
                  padding: "8px 0",
                  fontSize: 11,
                  fontFamily: "var(--font-mono)",
                  background: `oklch(0.72 ${c} ${h})`,
                  color: "oklch(0.15 0.02 250)",
                  border: "none",
                  borderRadius: 4,
                  cursor: "pointer",
                  fontWeight: 600,
                }}
              >
                {name}
              </button>
            ))}
          </div>
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<Landing />);
