/* eslint-disable */
// Stats strip, pricing, final CTA, footer.
//
// Redesigned 2026-09, second pass: the four-clip animated showreel from the
// previous version is gone too. It was built to replace fabricated
// testimonials with something honest, but it was still a performance —
// four looping scenes competing for attention. This page states things once,
// plainly, backed by a picture where a picture is the actual answer (the
// templates, in landing-features.jsx) and by nothing where it isn't.
//
// Every number here is read from the code that defines it: 19 templates
// (resumeThemes.ts), 10 job sources (the Apply page's source list), 15 tools
// (ToolsPage), 4 interview modes (InterviewPage's MODES). Pricing mirrors
// src/pages/PricingPage.tsx and the plan limits in app_settings — what
// Stripe actually charges and the server actually enforces.

const { useState: ls_useState, useEffect: ls_useEffect, useRef: ls_useRef } = React;

// ───────────────────────────────────────────────────────────────────────────────
function CountUp({ to, suffix = "", duration = 1000 }) {
  const [v, setV] = ls_useState(0);
  const ref = ls_useRef(null);
  const seen = ls_useRef(false);
  ls_useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !seen.current) {
          seen.current = true;
          const start = performance.now();
          const step = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setV(Math.round(to * eased));
            if (p < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.3 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref} className="mono">{v.toLocaleString()}{suffix}</span>;
}

function StatsStrip() {
  return (
    <section style={{ padding: "60px 0", background: "var(--ink)", color: "#fff" }}>
      <div className="container">
        <div className="stats-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 30 }}>
          {[
            { v: 19, label: "Résumé templates",              c: "var(--indigo)" },
            { v: 10, label: "Job boards searched at once",   c: "var(--amber)" },
            { v: 15, label: "Tools, one shared résumé",      c: "var(--mint)" },
            { v: 4,  label: "Interview modes, text to voice",c: "var(--rose)" },
          ].map((s, i) => (
            <div key={i} className="reveal" style={{ transitionDelay: `${i * 70}ms` }}>
              <div style={{ fontSize: "clamp(36px, 4.4vw, 52px)", fontWeight: 700, letterSpacing: "-0.03em", color: s.c, lineHeight: 1, marginBottom: 8 }}>
                <CountUp to={s.v} duration={800 + i * 120} />
              </div>
              <div style={{ fontSize: 13.5, color: "rgba(255,255,255,0.65)" }}>{s.label}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 800px) { .stats-grid { grid-template-columns: repeat(2, 1fr) !important; row-gap: 32px !important; } }
        @media (max-width: 480px) { .stats-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

// ───────────────────────────────────────────────────────────────────────────────
// Pricing — reads the live plan config from /api/plans (what the admin saved
// in Admin → Plans: labels, taglines, prices, and the feature bullets
// generated from each plan's limits and ticks). Nothing about a tier is
// hardcoded here except its accent colour and button style, keyed by id.
const TIER_STYLE = {
  free:  { color: "var(--fg-3)",   bg: "#fff",        ctaStyle: "ghost",   cta: () => "Start free" },
  basic: { color: "var(--amber)",  bg: "#fff",        ctaStyle: "ghost",   cta: (l) => `Get ${l}` },
  pro:   { color: "var(--indigo)", bg: "var(--ink)",  ctaStyle: "primary", cta: (l) => `Upgrade to ${l}` },
  team:  { color: "var(--rose)",   bg: "#fff",        ctaStyle: "ghost",   cta: (l) => `Upgrade to ${l}` },
};

// null = still loading, [] = the request failed (we then point at the in-app
// Pricing page instead of showing stale numbers).
function usePublicPlans() {
  const [plans, setPlans] = ls_useState(null);
  ls_useEffect(() => {
    let alive = true;
    fetch("/api/plans")
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
      .then((d) => { if (alive) setPlans(Array.isArray(d.plans) ? d.plans : []); })
      .catch(() => { if (alive) setPlans([]); });
    return () => { alive = false; };
  }, []);
  return plans;
}

function Pricing() {
  const [yearly, setYearly] = ls_useState(false);
  const plans = usePublicPlans();
  const tiers = (plans || []).map((p) => {
    const style = TIER_STYLE[p.id] || TIER_STYLE.basic;
    return {
      id: p.id, name: p.label, sub: p.tagline,
      monthly: p.priceMonthly, yearly: p.priceYearly,
      features: p.bullets || [], featured: p.featured,
      color: style.color, bg: style.bg, ctaStyle: style.ctaStyle, cta: style.cta(p.label),
      discount: p.yearlyDiscountPercent || 0,
    };
  });
  const maxSave = tiers.reduce((m, t) => Math.max(m, t.discount), 0);
  const gridCols = tiers.length ? tiers.map((t) => (t.featured ? "1.1fr" : "1fr")).join(" ") : "1fr";
  return (
    <section id="pricing" style={{ padding: "110px 0 100px", background: "var(--paper)" }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: "center", marginBottom: 36, maxWidth: 680, marginInline: "auto" }}>
          <div className="eye" style={{ marginBottom: 14 }}>PRICING</div>
          <h2 style={{ margin: 0, marginBottom: 14, fontSize: "clamp(32px, 4vw, 48px)", lineHeight: 1.06, letterSpacing: "-0.026em", fontWeight: 700 }}>
            One subscription. <span className="ed" style={{ fontWeight: 500, color: "var(--indigo)" }}>The whole studio.</span>
          </h2>
          <p style={{ fontSize: 16, color: "var(--ink-2)", margin: 0 }}>Cancel anytime.{maxSave > 0 ? ` Pay yearly and save up to ${maxSave}%.` : ""}</p>
        </div>

        <div className="reveal" style={{ display: "flex", justifyContent: "center", marginBottom: 36 }}>
          <div style={{ display: "inline-flex", padding: 4, borderRadius: 999, background: "#fff", border: "1px solid var(--line)" }}>
            {[["Monthly", false], ["Yearly", true]].map(([l, y]) => (
              <button key={l} onClick={() => setYearly(y)} style={{
                padding: "8px 18px", borderRadius: 999, fontSize: 14, fontWeight: 600,
                background: yearly === y ? "var(--ink)" : "transparent",
                color: yearly === y ? "#fff" : "var(--ink-2)",
                transition: "background 180ms, color 180ms",
              }}>{l}{y && <span style={{ marginLeft: 8, fontSize: 11, color: yearly ? "var(--mint)" : "var(--forest)", fontWeight: 700 }}>SAVE</span>}</button>
            ))}
          </div>
        </div>

        {plans === null && (
          <div style={{ textAlign: "center", padding: "40px 0", color: "var(--fg-3)", fontSize: 14 }}>Loading plans…</div>
        )}
        {plans !== null && tiers.length === 0 && (
          <div style={{ textAlign: "center", padding: "40px 0", color: "var(--fg-3)", fontSize: 14 }}>
            Plans are loading slowly right now — <a href="/pricing" style={{ color: "var(--indigo)", fontWeight: 600 }}>see current pricing in the app</a>.
          </div>
        )}
        <div className="pricing-grid" style={{ display: "grid", gridTemplateColumns: gridCols, gap: 16, maxWidth: 1180, marginInline: "auto", alignItems: "stretch" }}>
          {tiers.map((t, i) => {
            const dark = t.featured;
            const price = yearly ? t.yearly : t.monthly;
            return (
              <div key={t.id} className="reveal in" style={{
                background: t.bg, color: dark ? "#fff" : "var(--ink)",
                borderRadius: 18, padding: "28px 26px",
                border: dark ? "none" : "1px solid var(--line)",
                position: "relative",
                boxShadow: dark ? "0 20px 40px rgba(15,17,21,0.18)" : "none",
                transitionDelay: `${i * 70}ms`,
                display: "flex", flexDirection: "column",
              }}>
                {t.featured && (
                  <div style={{
                    position: "absolute", top: -11, left: "50%", transform: "translateX(-50%)",
                    background: "var(--indigo)", color: "#fff", fontSize: 10.5, fontWeight: 700,
                    padding: "5px 13px", borderRadius: 999, letterSpacing: "0.06em",
                  }}>MOST POPULAR</div>
                )}
                <div style={{ fontSize: 12.5, fontWeight: 600, color: t.color, marginBottom: 12, letterSpacing: "0.04em", textTransform: "uppercase" }}>{t.name}</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginBottom: 4 }}>
                  <span style={{ fontSize: 17, opacity: 0.7 }}>$</span>
                  <span style={{ fontSize: 48, fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1 }}>{price}</span>
                  {price > 0 && <span style={{ fontSize: 13, opacity: 0.7 }}>/{yearly ? "yr" : "mo"}</span>}
                </div>
                <div style={{ fontSize: 12.5, color: dark ? "rgba(255,255,255,0.6)" : "var(--fg-3)", marginBottom: 22 }}>{t.sub}</div>
                <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 11, marginBottom: 24, flex: 1 }}>
                  {t.features.map((f, j) => (
                    <li key={j} style={{ display: "flex", gap: 9, alignItems: "flex-start", fontSize: 13.5, color: dark ? "rgba(255,255,255,0.9)" : "var(--ink-2)" }}>
                      <span style={{ width: 18, height: 18, borderRadius: 999, background: t.color, color: "#fff", display: "grid", placeItems: "center", flexShrink: 0, marginTop: 1 }}>
                        <svg width="11" height="11" 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>
                      {f}
                    </li>
                  ))}
                </ul>
                <button style={{
                  padding: "13px 18px", borderRadius: 999, fontSize: 14, fontWeight: 600, cursor: "pointer",
                  background: t.ctaStyle === "primary" ? "var(--indigo)" : "transparent",
                  color: t.ctaStyle === "primary" ? "#fff" : (dark ? "#fff" : "var(--ink)"),
                  border: t.ctaStyle === "primary" ? "none" : `1.5px solid ${dark ? "rgba(255,255,255,0.2)" : "var(--ink)"}`,
                  width: "100%",
                }} onClick={() => { window.location.href = '/login'; }}>
                  {t.cta}
                </button>
              </div>
            );
          })}
        </div>

        <div className="reveal" style={{ textAlign: "center", marginTop: 30, fontSize: 12.5, color: "var(--fg-3)" }}>
          Secure checkout via Stripe · Receipts emailed automatically · Cancel from your profile any time
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .pricing-grid { grid-template-columns: 1fr !important; max-width: 460px !important; } }
      `}</style>
    </section>
  );
}

// ───────────────────────────────────────────────────────────────────────────────
function FinalCTA() {
  return (
    <section style={{ padding: "100px 0", background: "var(--ink)", color: "#fff" }}>
      <div className="container" style={{ textAlign: "center" }}>
        <div className="reveal" style={{ maxWidth: 720, marginInline: "auto" }}>
          <h2 style={{ margin: 0, marginBottom: 20, fontSize: "clamp(34px, 4.6vw, 58px)", lineHeight: 1.05, letterSpacing: "-0.03em", fontWeight: 700, color: "#fff" }}>
            Bring the résumé you have.<br /><span className="ed" style={{ fontWeight: 500, color: "var(--amber)" }}>Keep its format.</span>
          </h2>
          <p style={{ fontSize: 17, color: "rgba(255,255,255,0.75)", marginBottom: 30, lineHeight: 1.55 }}>
            Free to start. No card. Your résumé is never used to train AI models.
          </p>
          <button style={{
            padding: "15px 26px", background: "#fff", color: "var(--ink)",
            borderRadius: 999, fontSize: 15.5, fontWeight: 700,
            display: "inline-flex", alignItems: "center", gap: 10, cursor: "pointer",
          }} onClick={() => { window.location.href = '/login'; }}>
            Get started — it's free {LI.arrowRight}
          </button>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  const cols = [
    { name: "Studio",  links: [["Build a résumé", "/login"], ["Templates", "/login"], ["ATS scanner", "/login"], ["Cover letters", "/login"]] },
    { name: "Career",  links: [["Find jobs", "/login"], ["Job tracker", "/login"], ["Mock interview", "/login"], ["Career library", "/login"]] },
    { name: "Account", links: [["Sign in", "/login"], ["Pricing", "#pricing"], ["Contact", "mailto:hello@myresumestudio.app"]] },
    { name: "Legal",   links: [["Privacy", "/privacy"], ["Terms", "/terms"]] },
  ];
  return (
    <footer style={{ padding: "60px 0 32px", background: "var(--ink)", color: "#fff", borderTop: "1px solid rgba(255,255,255,0.08)" }}>
      <div className="container">
        <div className="footer-grid" style={{ display: "grid", gridTemplateColumns: "1.4fr repeat(4, 1fr)", gap: 36, marginBottom: 44, paddingBottom: 36, borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <StudioMark size={30} paper="var(--ink)" />
              <span style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-0.02em" }}>
                MyResume<span style={{ color: "var(--indigo)" }}>Studio</span>
              </span>
            </div>
            <p style={{ fontSize: 13, color: "rgba(255,255,255,0.6)", lineHeight: 1.55, maxWidth: 270 }}>
              The studio behind your career — from blank page to signed offer, in one place.
            </p>
          </div>
          {cols.map(col => (
            <div key={col.name}>
              <div style={{ fontSize: 11.5, fontWeight: 700, color: "#fff", letterSpacing: "0.08em", marginBottom: 14, textTransform: "uppercase" }}>{col.name}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 9 }}>
                {col.links.map(([l, href]) => (
                  <li key={l}><a href={href} style={{ fontSize: 13, color: "rgba(255,255,255,0.6)" }}
                    onMouseEnter={(e) => e.currentTarget.style.color = "#fff"}
                    onMouseLeave={(e) => e.currentTarget.style.color = "rgba(255,255,255,0.6)"}>{l}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12, fontSize: 12, color: "rgba(255,255,255,0.5)" }}>
          <div>© 2026 MyResumeStudio</div>
          <div>Résumé writing, job search, and interview practice — powered by Claude.</div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .footer-grid { grid-template-columns: 1fr 1fr !important; } }
        @media (max-width: 540px) { .footer-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </footer>
  );
}

Object.assign(window, { StatsStrip, Pricing, FinalCTA, Footer });
