// Trade Axis — full page sections
// Requires: React global + primitives + ProPanel/MT5Window + JournalApp

const { useState: useS, useEffect: useE, useMemo: useM, useRef: useR } = React;

function useI18n() {
  const [lang, setLang] = useS(() => localStorage.getItem("ta-lang") || "ua");
  useE(() => { localStorage.setItem("ta-lang", lang); document.documentElement.lang = lang; }, [lang]);
  const t = window.TA_STRINGS[lang];
  return [t, lang, setLang];
}

function useTweakState(TWEAKS) {
  const [theme, setTheme] = useS(() => localStorage.getItem("ta-theme") || TWEAKS.theme);
  const [accent, setAccent] = useS(() => localStorage.getItem("ta-accent") || TWEAKS.accent);
  useE(() => {
    document.documentElement.setAttribute("data-theme", theme);
    document.documentElement.setAttribute("data-accent", accent);
    localStorage.setItem("ta-theme", theme);
    localStorage.setItem("ta-accent", accent);
  }, [theme, accent]);
  return { theme, setTheme, accent, setAccent };
}

/* --------- Nav --------- */
function Nav({ t, lang, setLang, theme, setTheme }) {
  const base = (typeof window !== "undefined" && window.__TA_BASE_PATH) || "";
  const home = base + "index.html";
  const hashLink = (h) => base + "index.html" + h;
  const [scrolled, setScrolled] = useS(false);
  const [productsOpen, setProductsOpen] = useS(false);
  const closeTimer = useR(null);
  useE(() => {
    const fn = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", fn);
    return () => window.removeEventListener("scroll", fn);
  }, []);
  const openProducts = () => { clearTimeout(closeTimer.current); setProductsOpen(true); };
  const scheduleClose = () => { closeTimer.current = setTimeout(() => setProductsOpen(false), 180); };

  const products = [
    { name: "Trade Axis Pro",     href: base + "products/pro.html",     desc: t.nav.products_pro_desc,     accent: "var(--ta-blue)",  badge: "EA · MT5" },
    { name: "Trade Axis Journal", href: base + "products/journal.html", desc: t.nav.products_journal_desc, accent: "var(--ta-green)", badge: "Windows" },
    { name: "Trade Axis Copier",  href: base + "products/copier.html",  desc: t.nav.products_copier_desc,  accent: "#5FB8E8",         badge: "Windows · MT5" },
  ];

  return (
    <nav style={{
      position: "sticky", top: 0, zIndex: 50,
      background: scrolled ? "color-mix(in oklab, var(--bg) 80%, transparent)" : "transparent",
      backdropFilter: scrolled ? "blur(12px) saturate(1.2)" : "none",
      borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
      transition: "all .2s ease",
    }}>
      <div className="ta-container" style={{ display: "flex", alignItems: "center", padding: "18px 32px" }}>
        <a href={home} style={{ textDecoration: "none" }}><Logo /></a>
        <div style={{ marginLeft: 48, display: "flex", gap: 28, flex: 1 }}>
          {/* Products dropdown */}
          <div style={{ position: "relative" }} onMouseEnter={openProducts} onMouseLeave={scheduleClose}>
            <button onClick={() => setProductsOpen(o => !o)} style={{
              background: "none", border: "none", padding: 0,
              color: productsOpen ? "var(--text)" : "var(--text-2)",
              fontSize: 14, fontWeight: 500, cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 4,
              fontFamily: "inherit",
            }}>
              {t.nav.products}
              <svg width="10" height="10" viewBox="0 0 10 10" style={{ transform: productsOpen ? "rotate(180deg)" : "none", transition: "transform .15s" }}>
                <path d="M2 3.5l3 3 3-3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
              </svg>
            </button>
            {productsOpen && (
              <div style={{
                position: "absolute", top: "calc(100% + 14px)", left: -16,
                width: 380,
                background: "var(--bg-2)",
                border: "1px solid var(--line)",
                borderRadius: 14,
                boxShadow: "var(--shadow-lg)",
                padding: 8,
                display: "flex", flexDirection: "column", gap: 4,
              }}>
                {products.map((p, i) => (
                  <a key={i} href={p.href} style={{
                    display: "flex", gap: 14, padding: "12px 14px",
                    borderRadius: 10, textDecoration: "none",
                    color: "var(--text)",
                    transition: "background .12s",
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-3)"}
                  onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                    <div style={{
                      width: 38, height: 38, borderRadius: 8, flexShrink: 0,
                      background: "color-mix(in oklab, " + p.accent + " 14%, transparent)",
                      border: "1px solid color-mix(in oklab, " + p.accent + " 30%, transparent)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      color: p.accent, fontWeight: 700, fontSize: 14,
                      fontFamily: "var(--mono)",
                    }}>{p.name.split(" ").pop()[0]}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
                        <span style={{ fontWeight: 600, fontSize: 14, color: "var(--text)" }}>{p.name}</span>
                        <span className="ta-mono" style={{ fontSize: 9, color: "var(--text-3)", padding: "1px 6px", border: "1px solid var(--line)", borderRadius: 3, letterSpacing: ".06em" }}>{p.badge}</span>
                      </div>
                      <div style={{ fontSize: 12, color: "var(--text-2)", lineHeight: 1.45 }}>{p.desc}</div>
                    </div>
                  </a>
                ))}
              </div>
            )}
          </div>
          <a href={hashLink("#how")}      style={{ color: "var(--text-2)", fontSize: 14, fontWeight: 500 }}>{t.nav.how}</a>
          <a href={hashLink("#pricing")}  style={{ color: "var(--text-2)", fontSize: 14, fontWeight: 500 }}>{t.nav.pricing}</a>
          <a href={hashLink("#reviews")}  style={{ color: "var(--text-2)", fontSize: 14, fontWeight: 500 }}>{t.nav.reviews}</a>
          <a href={hashLink("#faq")}      style={{ color: "var(--text-2)", fontSize: 14, fontWeight: 500 }}>{t.nav.faq}</a>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {/* Theme toggle */}
          <div style={{ display: "flex", background: "var(--bg-3)", border: "1px solid var(--line)", borderRadius: 99, padding: 2 }}>
            {[
              { id: "dark",  icon: <svg width="12" height="12" viewBox="0 0 14 14"><path d="M11 8a4.5 4.5 0 0 1-5-6 5 5 0 1 0 5 6z" fill="currentColor"/></svg> },
              { id: "light", icon: <svg width="12" height="12" viewBox="0 0 14 14"><circle cx="7" cy="7" r="2.5" fill="currentColor"/><g stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"><line x1="7" y1="1.5" x2="7" y2="3"/><line x1="7" y1="11" x2="7" y2="12.5"/><line x1="1.5" y1="7" x2="3" y2="7"/><line x1="11" y1="7" x2="12.5" y2="7"/><line x1="3" y1="3" x2="4" y2="4"/><line x1="10" y1="10" x2="11" y2="11"/><line x1="3" y1="11" x2="4" y2="10"/><line x1="10" y1="4" x2="11" y2="3"/></g></svg> },
            ].map(opt => (
              <button key={opt.id} onClick={() => setTheme(opt.id)} aria-label={opt.id} style={{
                padding: "5px 9px", borderRadius: 99,
                background: theme === opt.id ? "var(--text)" : "transparent",
                color: theme === opt.id ? "var(--bg)" : "var(--text-2)",
                display: "flex", alignItems: "center",
                transition: "all .15s",
              }}>{opt.icon}</button>
            ))}
          </div>
          {/* Language toggle */}
          <div style={{ display: "flex", background: "var(--bg-3)", border: "1px solid var(--line)", borderRadius: 99, padding: 2 }}>
            {["ua", "ru", "en"].map(l => (
              <button key={l} onClick={() => setLang(l)} style={{
                padding: "5px 10px", borderRadius: 99,
                fontSize: 11, fontWeight: 600, letterSpacing: ".06em", textTransform: "uppercase",
                background: lang === l ? "var(--text)" : "transparent",
                color: lang === l ? "var(--bg)" : "var(--text-2)",
                transition: "all .15s",
              }}>{l}</button>
            ))}
          </div>
          <a href={hashLink("#pricing")} className="ta-btn ta-btn--accent" style={{ textDecoration: "none" }}>{t.nav.cta}</a>
        </div>
      </div>
    </nav>
  );
}

/* --------- Hero --------- */
function Hero({ t }) {
  return (
    <section style={{ position: "relative", padding: "60px 0 90px", overflow: "hidden" }} data-screen-label="01 Hero">
      <div className="ta-grid-bg" />
      {/* ambient blobs */}
      <div style={{ position: "absolute", top: -100, left: "10%", width: 500, height: 500, background: "radial-gradient(closest-side, color-mix(in oklab, var(--ta-blue) 30%, transparent), transparent 70%)", filter: "blur(30px)", pointerEvents: "none" }} />
      <div style={{ position: "absolute", bottom: -100, right: "5%", width: 500, height: 500, background: "radial-gradient(closest-side, color-mix(in oklab, var(--ta-green) 25%, transparent), transparent 70%)", filter: "blur(30px)", pointerEvents: "none" }} />

      <div className="ta-container" style={{ position: "relative" }}>
        <div className="ta-hero-grid">
          <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
            <div className="ta-kicker"><span className="dot" />{t.hero.eyebrow}</div>
            <h1 className="ta-display" style={{ fontSize: "clamp(40px, 5.4vw, 76px)", margin: 0 }}>
              {t.hero.title_a} <span style={{ color: "var(--ta-blue)" }}>{t.hero.title_b}</span>{t.hero.title_c}
            </h1>
            <p style={{ fontSize: 18, color: "var(--text-2)", maxWidth: 540, lineHeight: 1.55, margin: 0 }}>
              {t.hero.sub}
            </p>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              <a href="#pricing" className="ta-btn ta-btn--accent" style={{textDecoration:"none"}}>{t.hero.cta_primary} →</a>
              <a href="https://t.me/roman_dumanchuk" target="_blank" rel="noopener" className="ta-btn ta-btn--ghost" style={{textDecoration:"none"}}>▶ {t.hero.cta_secondary}</a>
            </div>
            <div style={{ display: "flex", gap: 16, flexWrap: "wrap", paddingTop: 12 }}>
              {[t.hero.badge_1, t.hero.badge_2, t.hero.badge_3].map((b, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--text-3)", fontSize: 13, fontFamily: "var(--mono)" }}>
                  <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 7l3 3 5-6" stroke="var(--ta-green)" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  {b}
                </div>
              ))}
            </div>
          </div>

          <div style={{ position: "relative" }}>
            {/* live pill top-right */}
            <div style={{ position: "absolute", top: -20, right: 0, zIndex: 3, display: "flex", alignItems: "center", gap: 8, padding: "8px 14px", background: "var(--bg-card)", border: "1px solid var(--line)", borderRadius: 99, fontFamily: "var(--mono)", fontSize: 12, fontWeight: 600 }}>
              <span className="ta-pulse-dot" />
              <span style={{ color: "var(--ta-green)" }}>{t.hero.ticker_live}</span>
              <span style={{ color: "var(--text-3)" }}>·</span>
              <span>XAUUSD <LiveNumber base={4834.64} swing={1.2} decimals={2} /></span>
            </div>
            <MT5Window strings={t.hero} />
            {/* floating telegram card */}
            <div className="ta-float" style={{
              position: "absolute", bottom: -30, left: -24, zIndex: 4,
              width: 260, padding: 14,
              background: "var(--bg-card)", border: "1px solid var(--line)", borderRadius: 14,
              boxShadow: "var(--shadow-lg)",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <div style={{ width: 24, height: 24, borderRadius: 99, background: "linear-gradient(135deg, #2AABEE, #229ED9)", display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontSize: 13 }}>✈</div>
                <span style={{ fontWeight: 600, fontSize: 13 }}>Trade Axis Bot</span>
                <span style={{ color: "var(--text-3)", fontSize: 11, marginLeft: "auto" }}>now</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--text-2)", lineHeight: 1.4 }}>
                <div>🟢 <b>XAUUSD SELL</b> · 0.10 @ 4835.27</div>
                <div style={{ color: "var(--text-3)", marginTop: 2 }}>Stop: 400 pts · Risk: $32 (0.72%)</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* --------- Stats strip --------- */
function StatsStrip({ t }) {
  const stats = [
    { n: "47", l: t.stats.countries },
    { n: "3 200+", l: t.stats.traders },
    { n: "1.8M", l: t.stats.trades },
    { n: "99.96%", l: t.stats.uptime },
  ];
  return (
    <section style={{ padding: "40px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
      <div className="ta-container" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24 }}>
        {stats.map((s, i) => (
          <div key={i} style={{ borderLeft: "2px solid var(--accent)", paddingLeft: 14 }}>
            <div className="ta-mono" style={{ fontSize: 32, fontWeight: 700, color: "var(--text)", letterSpacing: "-.02em" }}>{s.n}</div>
            <div style={{ color: "var(--text-3)", fontSize: 13, fontFamily: "var(--display)", fontWeight: 400, letterSpacing: ".01em", marginTop: 4 }}>{s.l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* --------- Product: Pro --------- */
function ProSection({ t }) {
  return (
    <section id="products" className="ta-section" data-screen-label="02 Product Pro">
      <div className="ta-container">
        <div className="ta-stack-below-1100">
          <div className="ta-sticky-off" style={{ position: "sticky", top: 100 }}>
            <div className="ta-kicker"><span className="dot" style={{ background: "var(--ta-blue)" }}/>{t.pro.kicker}</div>
            <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px 0 14px" }}>
              <span style={{ color: "var(--ta-blue)" }}>{t.pro.name}</span>
            </h2>
            <p style={{ fontSize: 20, color: "var(--text)", fontWeight: 500, lineHeight: 1.4, marginBottom: 16 }}>{t.pro.tagline}</p>
            <p style={{ color: "var(--text-2)", lineHeight: 1.6, marginBottom: 24 }}>{t.pro.desc}</p>
            <a href="products/pro.html" className="ta-btn ta-btn--ghost" style={{ textDecoration: "none" }}>{t.pro.explore} →</a>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
            <ProPanel strings={t.hero} compact />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
              {t.pro.features.map((f, i) => (
                <div key={i} style={{
                  background: "var(--bg-card)",
                  border: "1px solid var(--line)",
                  borderRadius: 14,
                  padding: 20,
                  display: "flex", flexDirection: "column", gap: 8,
                  gridColumn: i === 0 ? "1 / 3" : "auto",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                    <span className="ta-mono" style={{ color: "var(--ta-blue)", fontSize: 11, fontWeight: 600, background: "color-mix(in oklab, var(--ta-blue) 12%, transparent)", padding: "3px 8px", borderRadius: 4 }}>{String(i + 1).padStart(2, "0")}</span>
                    <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>{f.t}</h3>
                  </div>
                  <p style={{ color: "var(--text-2)", fontSize: 14, margin: 0, lineHeight: 1.55 }}>{f.d}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function JournalScaled({ strings }) {
  const outerRef = useR(null);
  const innerRef = useR(null);
  useE(() => {
    if (!outerRef.current || !innerRef.current) return;
    const fit = () => {
      const ow = outerRef.current.clientWidth;
      const iw = 1080;
      innerRef.current.style.width = iw + "px";
      const s = Math.min(1, ow / iw);
      innerRef.current.style.transform = `scale(${s})`;
      const ih = innerRef.current.scrollHeight;
      outerRef.current.style.height = (ih * s) + "px";
    };
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(outerRef.current);
    return () => ro.disconnect();
  }, []);
  return (
    <div className="ta-journal-scale" ref={outerRef}>
      <div className="ta-journal-inner" ref={innerRef}>
        <JournalApp strings={strings} />
      </div>
    </div>
  );
}

/* --------- Product: Journal --------- */
function JournalSection({ t }) {
  return (
    <section className="ta-section" style={{ background: "var(--bg-2)" }} data-screen-label="03 Product Journal">
      <div className="ta-container">
        <div className="ta-stack-below-1100--reverse">
          <div style={{ minWidth: 0 }}>
            <JournalScaled strings={t.journal} />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14, marginTop: 20 }}>
              {t.journal.features.map((f, i) => (
                <div key={i} style={{
                  background: "var(--bg-card)",
                  border: "1px solid var(--line)",
                  borderRadius: 14,
                  padding: 20,
                  display: "flex", flexDirection: "column", gap: 8,
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                    <span className="ta-mono" style={{ color: "var(--ta-green)", fontSize: 11, fontWeight: 600, background: "color-mix(in oklab, var(--ta-green) 12%, transparent)", padding: "3px 8px", borderRadius: 4 }}>{String(i + 1).padStart(2, "0")}</span>
                    <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>{f.t}</h3>
                  </div>
                  <p style={{ color: "var(--text-2)", fontSize: 14, margin: 0, lineHeight: 1.55 }}>{f.d}</p>
                </div>
              ))}
            </div>
          </div>

          <div className="ta-sticky-off" style={{ position: "sticky", top: 100 }}>
            <div className="ta-kicker"><span className="dot" style={{ background: "var(--ta-green)" }}/>{t.journal.kicker}</div>
            <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px 0 14px" }}>
              <span style={{ color: "var(--ta-green)" }}>{t.journal.name}</span>
            </h2>
            <p style={{ fontSize: 20, color: "var(--text)", fontWeight: 500, lineHeight: 1.4, marginBottom: 16 }}>{t.journal.tagline}</p>
            <p style={{ color: "var(--text-2)", lineHeight: 1.6, marginBottom: 24 }}>{t.journal.desc}</p>
            <a href="products/journal.html" className="ta-btn ta-btn--ghost" style={{ textDecoration: "none" }}>{t.journal.explore} →</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* --------- Product: Copier --------- */
function CopierScaled({ strings }) {
  const outerRef = useR(null);
  const innerRef = useR(null);
  useE(() => {
    if (!outerRef.current || !innerRef.current) return;
    const fit = () => {
      const ow = outerRef.current.clientWidth;
      const iw = 1080;
      innerRef.current.style.width = iw + "px";
      const s = Math.min(1, ow / iw);
      innerRef.current.style.transform = `scale(${s})`;
      const ih = innerRef.current.scrollHeight;
      outerRef.current.style.height = (ih * s) + "px";
    };
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(outerRef.current);
    return () => ro.disconnect();
  }, []);
  return (
    <div className="ta-journal-scale" ref={outerRef}>
      <div className="ta-journal-inner" ref={innerRef}>
        <CopierApp strings={strings} />
      </div>
    </div>
  );
}

function CopierSection({ t }) {
  const COPIER_ACCENT = "#5FB8E8"; // light blue
  return (
    <section id="copier" className="ta-section" data-screen-label="04 Product Copier">
      <div className="ta-container">
        <div className="ta-stack-below-1100">
          <div className="ta-sticky-off" style={{ position: "sticky", top: 100 }}>
            <div className="ta-kicker"><span className="dot" style={{ background: COPIER_ACCENT }}/>{t.copier.kicker}</div>
            <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px 0 14px" }}>
              <span style={{ color: COPIER_ACCENT }}>{t.copier.name}</span>
            </h2>
            <p style={{ fontSize: 20, color: "var(--text)", fontWeight: 500, lineHeight: 1.4, marginBottom: 16 }}>{t.copier.tagline}</p>
            <p style={{ color: "var(--text-2)", lineHeight: 1.6, marginBottom: 24 }}>{t.copier.desc}</p>
            <a href="products/copier.html" className="ta-btn ta-btn--ghost" style={{ textDecoration: "none" }}>{t.copier.explore} →</a>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 20, minWidth: 0 }}>
            <CopierScaled strings={t.copier} />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
              {t.copier.features.map((f, i) => (
                <div key={i} style={{
                  background: "var(--bg-card)",
                  border: "1px solid var(--line)",
                  borderRadius: 14,
                  padding: 20,
                  display: "flex", flexDirection: "column", gap: 8,
                  gridColumn: i === 0 ? "1 / 3" : "auto",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                    <span className="ta-mono" style={{ color: COPIER_ACCENT, fontSize: 11, fontWeight: 600, background: "color-mix(in oklab, " + COPIER_ACCENT + " 14%, transparent)", padding: "3px 8px", borderRadius: 4 }}>{String(i + 1).padStart(2, "0")}</span>
                    <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>{f.t}</h3>
                  </div>
                  <p style={{ color: "var(--text-2)", fontSize: 14, margin: 0, lineHeight: 1.55 }}>{f.d}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* --------- How it works --------- */
function HowSection({ t }) {
  return (
    <section id="how" className="ta-section" data-screen-label="04 How">
      <div className="ta-container">
        <div style={{ textAlign: "center", marginBottom: 50 }}>
          <div className="ta-kicker"><span className="dot" />{t.how.kicker}</div>
          <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px auto 0", maxWidth: 700 }}>{t.how.title}</h2>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, position: "relative" }}>
          {/* connector line */}
          <div style={{ position: "absolute", top: 36, left: "16%", right: "16%", height: 1, background: "linear-gradient(to right, transparent, var(--line-2) 20%, var(--line-2) 80%, transparent)", pointerEvents: "none" }} />
          {t.how.steps.map((s, i) => (
            <div key={i} style={{ position: "relative", padding: 28, background: "var(--bg-card)", border: "1px solid var(--line)", borderRadius: 18 }}>
              <div style={{
                width: 72, height: 72, borderRadius: 99,
                background: "linear-gradient(180deg, var(--bg-3), var(--bg-card))",
                border: "1px solid var(--line-2)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--display)", fontSize: 26, fontWeight: 700,
                color: i === 0 ? "var(--ta-blue)" : i === 1 ? "var(--ta-green)" : "var(--text)",
                marginBottom: 18,
                marginTop: -60,
                boxShadow: "var(--shadow-sm)",
              }}>{s.n}</div>
              <h3 style={{ fontSize: 22, margin: "0 0 10px", fontFamily: "var(--display)" }}>{s.t}</h3>
              <p style={{ color: "var(--text-2)", fontSize: 15, lineHeight: 1.55, margin: 0 }}>{s.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* --------- Pricing --------- */
function PricingSection({ t }) {
  const [modal, setModal] = useS(null); // null | {name, price}
  return (
    <section id="pricing" className="ta-section" style={{ background: "var(--bg-2)" }} data-screen-label="05 Pricing">
      {modal !== null && <PaymentsModal t={t} planName={modal?.name} planPrice={modal?.price} onClose={() => setModal(null)} />}
      <div className="ta-container">
        <div style={{ textAlign: "center", marginBottom: 50 }}>
          <div className="ta-kicker"><span className="dot" />{t.pricing.kicker}</div>
          <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px auto 12px", maxWidth: 700 }}>{t.pricing.title}</h2>
          <p style={{ fontSize: 17, color: "var(--text-2)", maxWidth: 560, margin: "0 auto" }}>{t.pricing.sub}</p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
          {t.pricing.plans.map((p, i) => (
            <div key={i} style={{
              background: p.highlight ? "var(--bg)" : "var(--bg-card)",
              border: p.highlight ? "1.5px solid var(--ta-green)" : "1px solid var(--line)",
              borderRadius: 22,
              padding: 30,
              position: "relative",
              display: "flex", flexDirection: "column", gap: 18,
              boxShadow: p.highlight ? "0 30px 80px -30px color-mix(in oklab, var(--ta-green) 50%, transparent)" : "none",
            }}>
              {p.badge && (
                <div style={{
                  position: "absolute", top: -12, right: 20,
                  padding: "4px 12px", background: "var(--ta-green)", color: "white",
                  borderRadius: 99, fontSize: 11, fontWeight: 700, letterSpacing: ".08em",
                }}>{p.badge}</div>
              )}
              <div>
                <h3 style={{ fontFamily: "var(--display)", fontSize: 24, margin: 0 }}>{p.name}</h3>
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                <span style={{ fontSize: 16, color: "var(--text-2)" }}>$</span>
                <span className="ta-mono" style={{ fontSize: 56, fontWeight: 700, letterSpacing: "-.03em" }}>{p.price}</span>
                <span style={{ fontSize: 14, color: "var(--text-3)", marginLeft: 4 }}>{p.period}</span>
              </div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                {p.features.map((f, j) => (
                  <li key={j} style={{ display: "flex", gap: 10, fontSize: 14, color: "var(--text-2)" }}>
                    <svg width="16" height="16" viewBox="0 0 14 14" style={{ marginTop: 3, flexShrink: 0 }}><path d="M3 7l3 3 5-6" stroke={p.highlight ? "var(--ta-green)" : "var(--text-3)"} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    {f}
                  </li>
                ))}
              </ul>
              <button onClick={() => setModal({name: p.name, price: p.price})} className={"ta-btn " + (p.highlight ? "ta-btn--accent" : "ta-btn--ghost")} style={{justifyContent:"center", marginTop:"auto"}}>{p.cta}</button>
            </div>
          ))}
        </div>
        <div style={{ textAlign: "center", color: "var(--text-3)", fontSize: 13, fontFamily: "var(--mono)", marginTop: 28 }}>{t.pricing.guarantee}</div>

        {/* Pointer to dedicated Copier pricing */}
        <div style={{
          marginTop: 32,
          padding: "20px 26px",
          background: "var(--bg-card)",
          border: "1px solid var(--line)",
          borderLeft: "3px solid #5FB8E8",
          borderRadius: 14,
          display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap",
        }}>
          <div style={{ flex: "1 1 360px", minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <span className="ta-mono" style={{ color: "#5FB8E8", fontSize: 11, fontWeight: 700, background: "color-mix(in oklab, #5FB8E8 14%, transparent)", padding: "3px 8px", borderRadius: 4, letterSpacing: ".08em" }}>COPIER MT5</span>
              <h3 style={{ margin: 0, fontSize: 17, fontFamily: "var(--display)" }}>{t.pricing.copier_pointer_title || "Trade Axis Copier — окрема підписка"}</h3>
            </div>
            <p style={{ color: "var(--text-2)", fontSize: 14, margin: 0, lineHeight: 1.55 }}>{t.pricing.copier_pointer_desc || "Платиться окремо від Pro + Journal. Тарифи нижче."}</p>
          </div>
          <a href="products/copier.html#copier-pricing" className="ta-btn ta-btn--ghost">{t.pricing.copier_pointer_cta || "До тарифів Copier"} →</a>
        </div>
      </div>
    </section>
  );
}

/* --------- FAQ --------- */
function FAQSection({ t }) {
  const [open, setOpen] = useS(0);
  return (
    <section id="faq" className="ta-section" data-screen-label="06 FAQ">
      <div className="ta-container" style={{ display: "grid", gridTemplateColumns: "minmax(0, 0.8fr) minmax(0, 1.2fr)", gap: 60 }}>
        <div>
          <div className="ta-kicker"><span className="dot" />{t.faq.kicker}</div>
          <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px 0 0" }}>{t.faq.title}</h2>
        </div>
        <div style={{ display: "flex", flexDirection: "column", borderTop: "1px solid var(--line)" }}>
          {t.faq.items.map((it, i) => (
            <div key={i} style={{ borderBottom: "1px solid var(--line)", padding: "24px 0" }}>
              <button
                onClick={() => setOpen(open === i ? -1 : i)}
                style={{ display: "flex", width: "100%", alignItems: "center", justifyContent: "space-between", textAlign: "left", fontSize: 18, fontWeight: 500, fontFamily: "var(--display)", color: "var(--text)" }}
              >
                <span>{it.q}</span>
                <span style={{ width: 28, height: 28, borderRadius: 99, background: "var(--bg-3)", border: "1px solid var(--line-2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, color: "var(--text-2)", flexShrink: 0, transform: open === i ? "rotate(45deg)" : "none", transition: "transform .2s" }}>+</span>
              </button>
              {open === i && (
                <p style={{ margin: "14px 0 0", color: "var(--text-2)", fontSize: 15, lineHeight: 1.6, maxWidth: 680 }}>{it.a}</p>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* --------- Final CTA --------- */
function CTASection({ t }) {
  const scrollToPricing = () => {
    const el = document.getElementById("pricing");
    if (el) el.scrollIntoView({ behavior: "smooth" });
  };
  return (
    <section className="ta-section" data-screen-label="07 CTA">
      <div className="ta-container">
        <div style={{
          padding: "60px 40px",
          borderRadius: 24,
          background: "linear-gradient(135deg, color-mix(in oklab, var(--ta-blue) 22%, var(--bg-2)), color-mix(in oklab, var(--ta-green) 22%, var(--bg-2)))",
          border: "1px solid var(--line-2)",
          textAlign: "center",
          position: "relative", overflow: "hidden",
        }}>
          <div className="ta-grid-bg" style={{ opacity: .25 }} />
          <div style={{ position: "relative" }}>
            <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 60px)", margin: "0 auto 16px", maxWidth: 800 }}>{t.cta.title}</h2>
            <p style={{ color: "var(--text-2)", fontSize: 17, margin: "0 auto 28px", maxWidth: 500 }}>{t.cta.sub}</p>
            <div style={{ display: "flex", justifyContent: "center", gap: 12, flexWrap: "wrap" }}>
              <button onClick={scrollToPricing} className="ta-btn ta-btn--accent">{t.cta.primary} →</button>
              <a href="https://t.me/roman_dumanchuk" target="_blank" rel="noopener" className="ta-btn ta-btn--ghost" style={{textDecoration:"none"}}>{t.cta.secondary}</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* --------- Footer --------- */
function Footer({ t }) {
  return (
    <footer style={{ background: "var(--bg-2)", borderTop: "1px solid var(--line)", padding: "60px 0 30px" }}>
      <div className="ta-container">
        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr 1fr", gap: 40, marginBottom: 48 }}>
          <div>
            <Logo />
            <p style={{ color: "var(--text-2)", fontSize: 14, maxWidth: 280, marginTop: 14, lineHeight: 1.6 }}>{t.footer.tagline}</p>
          </div>
          {[
            { title: t.footer.col_product, links: t.footer.links_product },
            { title: t.footer.col_resources, links: t.footer.links_resources },
            { title: t.footer.col_company, links: t.footer.links_company },
          ].map((col, i) => (
            <div key={i}>
              <h4 style={{ fontSize: 11, fontFamily: "var(--mono)", color: "var(--text-3)", letterSpacing: ".14em", textTransform: "uppercase", marginBottom: 14 }}>{col.title}</h4>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                {col.links.map((l, j) => (
                  <li key={j}><a href={l.includes("Telegram") || l.includes("спільнота") || l.includes("сообщество") || l.includes("community") ? "https://t.me/roman_dumanchuk" : "#"} target={l.includes("Telegram") || l.includes("спільнота") || l.includes("сообщество") || l.includes("community") ? "_blank" : ""} rel="noopener" style={{ color: "var(--text-2)", fontSize: 14 }}>{l}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ paddingTop: 24, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", gap: 24, alignItems: "start", flexWrap: "wrap" }}>
          <span style={{ color: "var(--text-3)", fontSize: 13 }}>{t.footer.rights}</span>
          <p style={{ color: "var(--text-3)", fontSize: 11, maxWidth: 680, margin: 0, lineHeight: 1.5 }}>{t.footer.risk}</p>
        </div>
      </div>
    </footer>
  );
}

/* --------- Tweaks panel --------- */
function TweaksPanel({ t, theme, setTheme, accent, setAccent, setTweakKeys }) {
  const [visible, setVisible] = useS(false);
  useE(() => {
    const handler = (e) => {
      if (e.data?.type === "__activate_edit_mode") setVisible(true);
      if (e.data?.type === "__deactivate_edit_mode") setVisible(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);
  if (!visible) return null;
  const set = (k, v) => {
    if (k === "theme") { setTheme(v); setTweakKeys({ theme: v }); }
    if (k === "accent") { setAccent(v); setTweakKeys({ accent: v }); }
  };
  return (
    <div className="ta-tweaks">
      <h4>{t.tweaks.title}</h4>
      <div className="group">
        <div className="group-title">{t.tweaks.theme}</div>
        <div className="seg">
          <button data-active={theme === "dark"} onClick={() => set("theme", "dark")}>{t.tweaks.dark}</button>
          <button data-active={theme === "light"} onClick={() => set("theme", "light")}>{t.tweaks.light}</button>
        </div>
      </div>
      <div className="group">
        <div className="group-title">{t.tweaks.accent}</div>
        <div className="seg">
          <button data-active={accent === "blue"} onClick={() => set("accent", "blue")}>{t.tweaks.blue}</button>
          <button data-active={accent === "green"} onClick={() => set("accent", "green")}>{t.tweaks.green}</button>
          <button data-active={accent === "balanced"} onClick={() => set("accent", "balanced")}>{t.tweaks.balanced}</button>
        </div>
      </div>
    </div>
  );
}

/* --------- Copier Pricing (3 tiers) --------- */
function CopierPricingSection({ t }) {
  const cp = t.copier_pricing;
  const COPIER_ACCENT = "#5FB8E8";
  const [modal, setModal] = useS(null);
  return (
    <section id="copier-pricing" className="ta-section" data-screen-label="06 Copier pricing">
      {modal !== null && <PaymentsModal t={t} planName={modal?.name} planPrice={modal?.price} onClose={() => setModal(null)} />}
      <div className="ta-container">
        <div style={{ textAlign: "center", marginBottom: 50 }}>
          <div className="ta-kicker" style={{ justifyContent: "center" }}><span className="dot" style={{ background: COPIER_ACCENT }} />{cp.kicker}</div>
          <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px auto 12px", maxWidth: 700 }}>{cp.title}</h2>
          <p style={{ fontSize: 17, color: "var(--text-2)", maxWidth: 620, margin: "0 auto" }}>{cp.sub}</p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
          {cp.plans.map((p, i) => (
            <div key={i} style={{
              background: p.highlight ? "var(--bg)" : "var(--bg-card)",
              border: p.highlight ? ("1.5px solid " + COPIER_ACCENT) : "1px solid var(--line)",
              borderRadius: 22,
              padding: 30,
              position: "relative",
              display: "flex", flexDirection: "column", gap: 18,
              boxShadow: p.highlight ? ("0 30px 80px -30px color-mix(in oklab, " + COPIER_ACCENT + " 50%, transparent)") : "none",
            }}>
              {p.badge && (
                <div style={{
                  position: "absolute", top: -12, right: 20,
                  padding: "4px 12px", background: COPIER_ACCENT, color: "#06121F",
                  borderRadius: 99, fontSize: 11, fontWeight: 700, letterSpacing: ".08em",
                }}>{p.badge}</div>
              )}
              <div>
                <h3 style={{ fontFamily: "var(--display)", fontSize: 24, margin: 0 }}>{p.name}</h3>
              </div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                <span style={{ fontSize: 16, color: "var(--text-2)" }}>$</span>
                <span className="ta-mono" style={{ fontSize: 56, fontWeight: 700, letterSpacing: "-.03em" }}>{p.price}</span>
                <span style={{ fontSize: 14, color: "var(--text-3)", marginLeft: 4 }}>{p.period}</span>
              </div>
              {p.note && <div className="ta-mono" style={{ fontSize: 12, color: COPIER_ACCENT, marginTop: -6 }}>{p.note}</div>}
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                {p.features.map((f, j) => (
                  <li key={j} style={{ display: "flex", gap: 10, fontSize: 14, color: "var(--text-2)" }}>
                    <svg width="16" height="16" viewBox="0 0 14 14" style={{ marginTop: 3, flexShrink: 0 }}><path d="M3 7l3 3 5-6" stroke={p.highlight ? COPIER_ACCENT : "var(--text-3)"} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    {f}
                  </li>
                ))}
              </ul>
              <button onClick={() => setModal({name: p.name, price: p.price})} className={"ta-btn " + (p.highlight ? "" : "ta-btn--ghost")} style={{
                justifyContent: "center", marginTop: "auto",
                ...(p.highlight ? { background: COPIER_ACCENT, color: "#06121F" } : {}),
              }}>{p.cta}</button>
            </div>
          ))}
        </div>
        {cp.guarantee && <div style={{ textAlign: "center", color: "var(--text-3)", fontSize: 13, fontFamily: "var(--mono)", marginTop: 28 }}>{cp.guarantee}</div>}
      </div>
    </section>
  );
}

/* --------- Payments Modal --------- */
const PAYMENT_DETAILS = {
  usdt: {
    icon: "₮", name: "USDT TRC20", sub: "USDT · Tron",
    fields: [
      { label: "Адреса", value: "TVDMQPFV11ppxtq5kDeeeiUBdKnih3X5fE", copy: true, mono: true, small: true },
      { label: "Мережа", value: "TRC20 (Tron)", copy: false },
    ],
  },
  binance: {
    icon: "🔶", name: "Binance Pay", sub: "USDT · BTC · BNB",
    fields: [
      { label: "Binance UID", value: "27857831", copy: true },
      { label: "Валюта", value: "USDT / BTC / BNB", copy: false },
    ],
  },
};

function PaymentsModal({ t, planName, planPrice, onClose }) {
  const [step, setStep] = useS(1);
  const [form, setForm] = useS({ name: "", email: "", telegram: "", country: "" });
  const [payMethod, setPayMethod] = useS("usdt");
  const [copied, setCopied] = useS(null);
  const [submitting, setSubmitting] = useS(false);
  const [submitError, setSubmitError] = useS("");
  const [extraAccounts, setExtraAccounts] = useS(0);
  const [couponCode, setCouponCode] = useS("");
  const [couponApplied, setCouponApplied] = useS(null); // { discount, partner, label }
  const [couponError, setCouponError] = useS("");
  const [couponLoading, setCouponLoading] = useS(false);

  const isTrial = planPrice === "0" || planPrice === 0;
  const isYearly = planName && (planName.includes("рік") || planName.includes("год") || planName.includes("year"));
  const baseAccounts = 3;
  const totalAccounts = baseAccounts + extraAccounts;
  const priceBeforeDiscount = planPrice ? Number(planPrice) + extraAccounts * 10 : planPrice;
  const discountAmount = couponApplied ? Math.round(priceBeforeDiscount * couponApplied.client_discount / 100) : 0;
  const totalPrice = priceBeforeDiscount ? priceBeforeDiscount - discountAmount : priceBeforeDiscount;

  const applyCoupon = async () => {
    if (!couponCode.trim()) return;
    setCouponLoading(true);
    setCouponError("");
    setCouponApplied(null);
    try {
      const res = await fetch("/.netlify/functions/coupon", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ coupon: couponCode.trim() }),
      });
      const data = await res.json();
      if (data.status === "ok") {
        setCouponApplied(data);
      } else {
        setCouponError(data.message || "Невірний купон");
      }
    } catch (e) {
      setCouponError("Помилка перевірки. Спробуйте ще раз.");
    }
    setCouponLoading(false);
  };

  useE(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, []);

  const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const isStep1Valid = form.name.trim() && form.email.trim() && form.country.trim() && (isTrial || form.telegram.trim());

  const copyText = (text, id) => {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(id);
      setTimeout(() => setCopied(null), 2000);
    });
  };

  // Для тріалу — відправляємо на trial endpoint і одразу step 3
  const handleTrialSubmit = async () => {
    setSubmitting(true);
    setSubmitError("");
    try {
      const params = new URLSearchParams({
        action: "trial",
        email: form.email.trim(),
        name: form.name.trim(),
        product: "pro+journal",
      });
      const res = await fetch("/.netlify/functions/license?" + params.toString());
      const data = await res.json();
      if (data.status === "ok") {
        setStep(3);
      } else if (data.status === "trial_exists") {
        setSubmitError("Тріал для цього email вже видано. Перевірте пошту або зверніться до підтримки.");
      } else {
        setSubmitError(data.message || "Помилка. Спробуйте ще раз або напишіть нам.");
      }
    } catch (e) {
      setSubmitError("Помилка з'єднання. Напишіть нам у Telegram.");
    }
    setSubmitting(false);
  };

  const handlePaid = async () => {
    setSubmitting(true);
    setSubmitError("");
    try {
      const res = await fetch("/.netlify/functions/order", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          telegram: form.telegram,
          country: form.country,
          plan: planName || "",
          price: totalPrice || "",
          accounts: totalAccounts,
          coupon: couponApplied ? couponCode.toUpperCase() : "",
          discount: couponApplied ? `${couponApplied.client_discount}%` : "",
          partner: couponApplied ? couponApplied.partner : "",
          payment_method: PAYMENT_DETAILS[payMethod]?.name || payMethod,
        }),
      });
      const data = await res.json();
      if (data.status === "error" || data.status === "server_error") {
        setSubmitError(data.message || "Помилка відправки. Спробуйте ще раз.");
      } else {
        setStep(3);
      }
    } catch (e) {
      setSubmitError("Помилка з'єднання. Напишіть нам у Telegram.");
    }
    setSubmitting(false);
  };

  const p = t.payments;
  const det = PAYMENT_DETAILS[payMethod];

  const stepStyle = (n) => ({
    display: "flex", alignItems: "center", gap: 6,
  });
  const numStyle = (n) => ({
    width: 22, height: 22, borderRadius: 99, fontSize: 11, fontWeight: 600,
    display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
    background: step === n ? "var(--accent)" : step > n ? "color-mix(in oklab, var(--accent) 30%, var(--bg-card))" : "var(--bg-3)",
    color: step === n ? "#fff" : step > n ? "var(--accent)" : "var(--text-3)",
    border: step > n ? "1px solid color-mix(in oklab, var(--accent) 40%, transparent)" : "1px solid var(--line)",
  });
  const lblStyle = (n) => ({
    fontSize: 12, fontFamily: "var(--mono)",
    color: step === n ? "var(--text)" : "var(--text-3)",
    fontWeight: step === n ? 600 : 400,
  });

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 9999,
        background: "rgba(0,0,0,0.75)",
        backdropFilter: "blur(6px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: "16px",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--bg)",
          border: "1px solid var(--line-2)",
          borderRadius: 24,
          padding: "28px 28px 32px",
          width: "100%",
          maxWidth: 580,
          maxHeight: "92vh",
          overflowY: "auto",
          position: "relative",
          boxShadow: "0 40px 120px rgba(0,0,0,0.6)",
        }}
      >
        {/* Close */}
        <button onClick={onClose} style={{
          position: "absolute", top: 14, right: 14,
          width: 30, height: 30, borderRadius: 99,
          background: "var(--bg-3)", border: "1px solid var(--line)",
          color: "var(--text-2)", fontSize: 17, cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>×</button>

        {/* Steps indicator */}
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 24, paddingRight: 40 }}>
          <div style={stepStyle(1)}><div style={numStyle(1)}>1</div><span style={lblStyle(1)}>Ваші дані</span></div>
          {!isTrial && <>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
            <div style={stepStyle(2)}><div style={numStyle(2)}>2</div><span style={lblStyle(2)}>Оплата</span></div>
          </>}
          <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
          <div style={stepStyle(isTrial ? 2 : 3)}><div style={numStyle(isTrial ? 2 : 3)}>{isTrial ? 2 : 3}</div><span style={lblStyle(isTrial ? 2 : 3)}>Готово</span></div>
        </div>

        {/* Plan badge */}
        {planName && (
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "4px 12px", marginBottom: 20,
            background: "color-mix(in oklab, var(--accent) 12%, var(--bg-card))",
            border: "1px solid color-mix(in oklab, var(--accent) 30%, transparent)",
            borderRadius: 99, fontSize: 12, fontFamily: "var(--mono)",
            color: "var(--accent)", fontWeight: 600,
          }}>
            ✦ {planName}{totalPrice ? ` · $${totalPrice}` : ""}{couponApplied ? ` (-${couponApplied.client_discount}%)` : ""}
          </div>
        )}

        {/* ── STEP 1: Form ── */}
        {step === 1 && (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }}>
              {[
                { k: "name", label: "Ім'я", placeholder: "Іван", type: "text" },
                { k: "email", label: "Email", placeholder: "ivan@gmail.com", type: "email" },
                ...(!isTrial ? [{ k: "telegram", label: "Telegram", placeholder: "@username", type: "text" }] : []),
                { k: "country", label: "Країна", placeholder: "Україна", type: "text" },
              ].map(({ k, label, placeholder, type }) => (
                <div key={k}>
                  <div style={{ fontSize: 11, fontFamily: "var(--mono)", color: "var(--text-3)", marginBottom: 5, letterSpacing: ".06em", textTransform: "uppercase" }}>
                    {label} <span style={{ color: "var(--ta-coral, #e07)" }}>*</span>
                  </div>
                  <input
                    type={type}
                    value={form[k]}
                    onChange={(e) => setField(k, e.target.value)}
                    placeholder={placeholder}
                    style={{
                      width: "100%", boxSizing: "border-box",
                      background: "var(--bg-card)", border: "1px solid var(--line)",
                      borderRadius: 10, padding: "9px 12px",
                      fontSize: 14, color: "var(--text)",
                      fontFamily: k === "telegram" ? "var(--mono)" : "inherit",
                      outline: "none",
                    }}
                  />
                </div>
              ))}
            </div>

            <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 20, display: "flex", alignItems: "flex-start", gap: 6 }}>
              <span style={{ flexShrink: 0 }}>💌</span>
              {isTrial
                ? "Ліцензійний ключ на 14 днів надійде на вказаний email одразу після підтвердження."
                : "На вказаний email надійде ліцензійний ключ після підтвердження оплати."}
            </div>

            {submitError && (
              <div style={{ color: "#e53e3e", fontSize: 13, marginBottom: 12, padding: "8px 12px", background: "color-mix(in oklab, #e53e3e 10%, transparent)", borderRadius: 8 }}>
                {submitError}
              </div>
            )}

            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <button
                onClick={isTrial ? handleTrialSubmit : () => setStep(2)}
                disabled={!isStep1Valid || submitting}
                className="ta-btn ta-btn--accent"
                style={{ opacity: (isStep1Valid && !submitting) ? 1 : 0.4, cursor: (isStep1Valid && !submitting) ? "pointer" : "not-allowed" }}
              >
                {submitting ? "Надсилання..." : isTrial ? "Отримати ключ →" : "Далі →"}
              </button>
            </div>

            {/* Вибір рахунків для річного тарифу */}
            {isYearly && isStep1Valid && (
              <div style={{ marginTop: 20, background: "var(--bg-card)", border: "1px solid var(--line)", borderRadius: 14, padding: "16px 18px" }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text)", marginBottom: 10 }}>
                  Кількість торгових рахунків MT5
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
                  {[0, 1, 2, 3, 4, 5, 6, 7].map(extra => (
                    <button
                      key={extra}
                      onClick={() => setExtraAccounts(extra)}
                      style={{
                        width: 40, height: 40, borderRadius: 8,
                        border: extraAccounts === extra ? "1.5px solid var(--accent)" : "1px solid var(--line)",
                        background: extraAccounts === extra ? "color-mix(in oklab, var(--accent) 12%, var(--bg))" : "var(--bg)",
                        color: extraAccounts === extra ? "var(--accent)" : "var(--text-2)",
                        fontWeight: 600, fontSize: 14, cursor: "pointer",
                      }}
                    >{baseAccounts + extra}</button>
                  ))}
                </div>
                <div style={{ fontSize: 12, color: "var(--text-3)" }}>
                  Базово 3 рахунки включено · +$10 за кожен додатковий
                  {extraAccounts > 0 && <span style={{ color: "var(--accent)", marginLeft: 8 }}>+${extraAccounts * 10} до суми</span>}
                </div>
              </div>
            )}
          </div>
        )}

        {/* ── STEP 2: Payment ── */}
        {step === 2 && (
          <div>
            {/* Method selector */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16 }}>
              {Object.entries(PAYMENT_DETAILS).map(([key, d]) => (
                <button
                  key={key}
                  onClick={() => setPayMethod(key)}
                  style={{
                    background: payMethod === key ? "color-mix(in oklab, var(--accent) 10%, var(--bg-card))" : "var(--bg-card)",
                    border: payMethod === key ? "1.5px solid var(--accent)" : "1px solid var(--line)",
                    borderRadius: 14, padding: "14px 16px", cursor: "pointer",
                    textAlign: "left", transition: "all .15s",
                  }}
                >
                  <div style={{ fontSize: 18, marginBottom: 6 }}>{d.icon}</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text)" }}>{d.name}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "var(--mono)" }}>{d.sub}</div>
                </button>
              ))}
            </div>

            {/* Details */}
            <div style={{ background: "var(--bg-card)", border: "1px solid var(--line)", borderRadius: 14, padding: "16px 18px", marginBottom: 16 }}>
              {det.fields.map((f, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "6px 0", borderBottom: i < det.fields.length - 1 ? "1px solid var(--line)" : "none" }}>
                  <span style={{ fontSize: 12, color: "var(--text-3)", fontFamily: "var(--mono)" }}>{f.label}</span>
                  <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    {f.link
                      ? <a href={f.link} target="_blank" rel="noopener" style={{ fontSize: 12, color: "var(--accent)", textDecoration: "none" }}>Написати в Telegram →</a>
                      : <span style={{ fontSize: f.small ? 10 : 13, fontFamily: "var(--mono)", color: "var(--text-2)", wordBreak: "break-all", maxWidth: 240, textAlign: "right" }}>{f.value}</span>
                    }
                    {f.copy && (
                      <button onClick={() => copyText(f.value, i)} style={{
                        padding: "3px 8px", borderRadius: 6, border: "1px solid var(--line)",
                        background: copied === i ? "color-mix(in oklab, var(--accent) 12%, var(--bg))" : "var(--bg)",
                        color: copied === i ? "var(--accent)" : "var(--text-3)",
                        fontSize: 11, fontFamily: "var(--mono)", cursor: "pointer",
                      }}>{copied === i ? "✓" : "Копіювати"}</button>
                    )}
                  </span>
                </div>
              ))}
            </div>

            {/* Купон знижки */}
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, fontFamily: "var(--mono)", color: "var(--text-3)", marginBottom: 6, letterSpacing: ".06em", textTransform: "uppercase" }}>
                Купон знижки
              </div>
              {couponApplied ? (
                <div style={{ display: "flex", alignItems: "center", gap: 10, background: "color-mix(in oklab, var(--accent) 10%, var(--bg-card))", border: "1px solid color-mix(in oklab, var(--accent) 30%, transparent)", borderRadius: 10, padding: "10px 14px" }}>
                  <span style={{ fontSize: 18 }}>🎉</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "var(--accent)" }}>{couponCode.toUpperCase()} — -{couponApplied.client_discount}% знижка</div>
                    <div style={{ fontSize: 11, color: "var(--text-3)" }}>Економія: ${discountAmount}</div>
                  </div>
                  <button onClick={() => { setCouponApplied(null); setCouponCode(""); }} style={{ background: "none", border: "none", color: "var(--text-3)", cursor: "pointer", fontSize: 16 }}>×</button>
                </div>
              ) : (
                <div style={{ display: "flex", gap: 8 }}>
                  <input
                    type="text"
                    value={couponCode}
                    onChange={(e) => { setCouponCode(e.target.value.toUpperCase()); setCouponError(""); }}
                    onKeyDown={(e) => e.key === "Enter" && applyCoupon()}
                    placeholder="PARTNER20"
                    style={{
                      flex: 1, background: "var(--bg-card)", border: "1px solid var(--line)",
                      borderRadius: 10, padding: "9px 12px", fontSize: 14,
                      fontFamily: "var(--mono)", color: "var(--text)", letterSpacing: ".05em",
                      outline: "none",
                    }}
                  />
                  <button onClick={applyCoupon} disabled={couponLoading || !couponCode.trim()} style={{
                    padding: "9px 16px", borderRadius: 10, border: "1px solid var(--line)",
                    background: "var(--bg-card)", color: "var(--text-2)", fontSize: 13,
                    cursor: couponCode.trim() ? "pointer" : "not-allowed",
                    opacity: couponCode.trim() ? 1 : 0.5,
                    fontFamily: "var(--mono)", whiteSpace: "nowrap",
                  }}>
                    {couponLoading ? "..." : "Застосувати"}
                  </button>
                </div>
              )}
              {couponError && (
                <div style={{ fontSize: 12, color: "#e44", marginTop: 6 }}>{couponError}</div>
              )}
            </div>

            {/* Сума до оплати */}
            <div style={{
              background: "var(--bg-card)", border: "1px solid var(--line)",
              borderRadius: 14, padding: "14px 18px", marginBottom: 16,
              display: "flex", justifyContent: "space-between", alignItems: "center",
            }}>
              <div style={{ fontSize: 13, color: "var(--text-3)", fontFamily: "var(--mono)" }}>До оплати:</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                {couponApplied && (
                  <span style={{ fontSize: 14, color: "var(--text-3)", textDecoration: "line-through" }}>
                    ${priceBeforeDiscount}
                  </span>
                )}
                <span style={{ fontSize: 28, fontWeight: 700, fontFamily: "var(--mono)", color: couponApplied ? "var(--accent)" : "var(--text)" }}>
                  ${totalPrice}
                </span>
                {couponApplied && (
                  <span style={{ fontSize: 12, color: "var(--accent)", fontFamily: "var(--mono)" }}>
                    -{couponApplied.client_discount}%
                  </span>
                )}
              </div>
            </div>

            <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 20 }}>
              💡 Після оплати натисніть кнопку нижче — ваші дані запишемо і зв'яжемось з вами.
            </div>

            <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 16, textAlign: "center" }}>
              Інші способи оплати (PayPal, Wise, банк) —{" "}
              <a href="https://t.me/roman_dumanchuk" target="_blank" rel="noopener" style={{ color: "var(--accent)" }}>напишіть у Telegram</a>
            </div>

            {submitError && (
              <div style={{ fontSize: 13, color: "var(--ta-coral, #e44)", background: "color-mix(in oklab, #e44 8%, var(--bg))", border: "1px solid color-mix(in oklab, #e44 20%, transparent)", borderRadius: 8, padding: "10px 14px", marginBottom: 14 }}>
                {submitError}
              </div>
            )}

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <button onClick={() => setStep(1)} className="ta-btn ta-btn--ghost" style={{ fontSize: 13 }}>← Назад</button>
              <button onClick={handlePaid} disabled={submitting} className="ta-btn ta-btn--accent" style={{ opacity: submitting ? 0.6 : 1 }}>
                {submitting ? "Надсилаємо..." : "Я оплатив ✓"}
              </button>
            </div>
          </div>
        )}

        {/* ── STEP 3: Done ── */}
        {step === 3 && (
          <div style={{ textAlign: "center", padding: "12px 0 8px" }}>
            <div style={{
              width: 60, height: 60, borderRadius: 99, margin: "0 auto 20px",
              background: "color-mix(in oklab, var(--accent) 15%, var(--bg-card))",
              border: "1px solid color-mix(in oklab, var(--accent) 30%, transparent)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 28,
            }}>✓</div>
            <div style={{ fontSize: 20, fontFamily: "var(--display)", fontWeight: 600, marginBottom: 10 }}>
              {isTrial ? "Ключ надіслано!" : "Дякуємо!"}
            </div>
            <div style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.6, maxWidth: 380, margin: "0 auto 24px" }}>
              {isTrial
                ? <>Ваш безкоштовний ключ на <strong>14 днів</strong> надіслано на <strong>{form.email}</strong>. Перевірте пошту і активуйте додаток.</>
                : <>Ваше замовлення отримано. Ми перевіримо оплату і надішлемо ліцензійний ключ на <strong>{form.email}</strong> протягом кількох хвилин.</>
              }
            </div>
            <a
              href="https://t.me/roman_dumanchuk"
              target="_blank"
              rel="noopener"
              className="ta-btn ta-btn--accent"
              style={{ textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 8 }}
            >
              ✈ Написати в Telegram
            </a>
            <div style={{ marginTop: 12, fontSize: 12, color: "var(--text-3)" }}>
              {isTrial
                ? "Якщо не отримали ключ протягом 5 хв — перевірте спам або зв'яжіться з нами."
                : "Якщо не отримали ключ протягом 30 хв — зв'яжіться з нами."}
            </div>
          </div>
        )}

      </div>
    </div>
  );
}

/* --------- Reviews carousel --------- */
function ReviewsSection({ t }) {
  const items = t.reviews.items;
  const trackRef = useR(null);
  const scrollBy = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * (el.clientWidth * 0.85), behavior: "smooth" });
  };
  return (
    <section id="reviews" className="ta-section" data-screen-label="08 Reviews">
      <div className="ta-container">
        <div style={{ display: "flex", alignItems: "end", justifyContent: "space-between", gap: 32, marginBottom: 36, flexWrap: "wrap" }}>
          <div>
            <div className="ta-kicker"><span className="dot" />{t.reviews.kicker}</div>
            <h2 className="ta-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "18px 0 8px", maxWidth: 600 }}>{t.reviews.title}</h2>
            <p style={{ fontSize: 15, color: "var(--text-3)", margin: 0, fontFamily: "var(--mono)" }}>{t.reviews.sub}</p>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => scrollBy(-1)} className="ta-btn ta-btn--ghost" style={{ padding: 0, width: 44, height: 44, justifyContent: "center" }}>←</button>
            <button onClick={() => scrollBy(1)} className="ta-btn ta-btn--ghost" style={{ padding: 0, width: 44, height: 44, justifyContent: "center" }}>→</button>
          </div>
        </div>
      </div>
      <div ref={trackRef} style={{
        display: "flex",
        gap: 18,
        overflowX: "auto",
        padding: "8px max(32px, calc((100vw - 1280px) / 2 + 32px)) 24px",
        scrollSnapType: "x mandatory",
        scrollbarWidth: "none",
      }}>
        <style>{`#reviews ::-webkit-scrollbar { display: none; }`}</style>
        {items.map((r, i) => (
          <article key={i} style={{
            flex: "0 0 360px",
            background: "var(--bg-card)",
            border: "1px solid var(--line)",
            borderRadius: 18,
            padding: 26,
            display: "flex",
            flexDirection: "column",
            gap: 16,
            scrollSnapAlign: "start",
          }}>
            <div style={{ display: "flex", gap: 2 }}>
              {Array.from({ length: 5 }).map((_, k) => (
                <svg key={k} width="16" height="16" viewBox="0 0 16 16">
                  <path d="M8 1l2.2 4.5L15 6.2l-3.5 3.4L12.4 15 8 12.6 3.6 15l.9-5.4L1 6.2l4.8-.7L8 1z" fill={k < r.stars ? "var(--ta-green)" : "var(--line-2)"} />
                </svg>
              ))}
            </div>
            <p style={{ margin: 0, fontSize: 15, lineHeight: 1.55, color: "var(--text)", flex: 1 }}>“{r.quote}”</p>
            <div style={{ paddingTop: 14, borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{
                width: 38, height: 38, borderRadius: 99,
                background: "linear-gradient(135deg, var(--ta-blue), var(--ta-green))",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--display)", fontWeight: 700, color: "white", fontSize: 15,
              }}>{r.name.charAt(0)}</div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{r.name}</div>
                <div style={{ color: "var(--text-3)", fontSize: 12, fontFamily: "var(--mono)" }}>{r.role}</div>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* --------- AI chat launcher --------- */
function AIChatLauncher({ t }) {
  const [open, setOpen] = useS(false);
  const [messages, setMessages] = useS([{ role: "bot", text: t.chat.first_message }]);
  const [input, setInput] = useS("");
  const [busy, setBusy] = useS(false);
  const messagesEndRef = useR(null);

  useE(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages]);

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || busy) return;
    const newMessages = [...messages, { role: "user", text: q }];
    setMessages(newMessages);
    setInput("");
    setBusy(true);
    try {
      // Конвертуємо в формат Anthropic API
      const apiMessages = newMessages
        .filter(m => m.role !== "bot" || m !== newMessages[0]) // прибираємо перше привітання
        .map(m => ({ role: m.role === "bot" ? "assistant" : "user", content: m.text }));

      const res = await fetch("/.netlify/functions/claude", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: apiMessages }),
      });
      const data = await res.json();
      setMessages((m) => [...m, { role: "bot", text: data.reply || "—" }]);
    } catch (e) {
      setMessages((m) => [...m, { role: "bot", text: "Виникла помилка. Спробуйте ще раз або напишіть у Telegram." }]);
    }
    setBusy(false);
  };
  return (
    <>
      {/* Launcher button */}
      <button
        onClick={() => setOpen((v) => !v)}
        aria-label={t.chat.launcher}
        style={{
          position: "fixed", right: 24, bottom: 24, zIndex: 60,
          width: 60, height: 60, borderRadius: 99,
          background: "linear-gradient(135deg, var(--ta-blue), var(--ta-green))",
          color: "white",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 18px 40px -10px color-mix(in oklab, var(--ta-blue) 60%, transparent)",
          border: "1px solid color-mix(in oklab, white 18%, transparent)",
        }}
      >
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        ) : (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a8 8 0 0 1-11.5 7.2L3 21l1.8-6.5A8 8 0 1 1 21 12z"/></svg>
        )}
      </button>

      {/* Panel */}
      {open && (
        <div style={{
          position: "fixed", right: 24, bottom: 96, zIndex: 60,
          width: 380, maxWidth: "calc(100vw - 48px)",
          height: 520, maxHeight: "calc(100vh - 140px)",
          background: "var(--bg-card)",
          border: "1px solid var(--line-2)",
          borderRadius: 20,
          boxShadow: "0 30px 80px -20px rgba(0,0,0,.6)",
          display: "flex", flexDirection: "column",
          overflow: "hidden",
        }}>
          <header style={{
            padding: "16px 18px",
            background: "linear-gradient(135deg, color-mix(in oklab, var(--ta-blue) 14%, var(--bg-card)), color-mix(in oklab, var(--ta-green) 12%, var(--bg-card)))",
            borderBottom: "1px solid var(--line)",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 8, height: 8, borderRadius: 99, background: "var(--ta-green)", boxShadow: "0 0 0 4px color-mix(in oklab, var(--ta-green) 24%, transparent)" }} />
              <div style={{ fontFamily: "var(--display)", fontSize: 15, fontWeight: 600 }}>{t.chat.title}</div>
            </div>
            <div style={{ color: "var(--text-3)", fontSize: 12, marginTop: 4 }}>{t.chat.sub}</div>
          </header>
          <div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 12 }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.role === "user" ? "flex-end" : "flex-start",
                maxWidth: "82%",
                padding: "10px 14px",
                background: m.role === "user" ? "var(--ta-blue)" : "var(--bg-2)",
                color: m.role === "user" ? "white" : "var(--text)",
                borderRadius: 14,
                borderTopRightRadius: m.role === "user" ? 4 : 14,
                borderTopLeftRadius: m.role === "user" ? 14 : 4,
                fontSize: 14, lineHeight: 1.5,
                whiteSpace: "pre-wrap",
                border: m.role === "user" ? "none" : "1px solid var(--line)",
              }}>{m.text}</div>
            ))}
            {busy && (
              <div style={{ alignSelf: "flex-start", padding: "10px 14px", background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 14, fontSize: 14, color: "var(--text-3)" }}>...</div>
            )}
            <div ref={messagesEndRef} />
            {messages.length <= 1 && (
              <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6 }}>
                <div style={{ fontSize: 11, fontFamily: "var(--mono)", color: "var(--text-3)", letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 4 }}>{t.chat.examples ? "" : ""}</div>
                {t.chat.examples.map((ex, i) => (
                  <button key={i} onClick={() => send(ex)} style={{
                    textAlign: "left",
                    padding: "10px 12px",
                    background: "var(--bg)",
                    border: "1px solid var(--line)",
                    borderRadius: 10,
                    fontSize: 13,
                    color: "var(--text-2)",
                  }}>{ex}</button>
                ))}
              </div>
            )}
          </div>
          <footer style={{ padding: 14, borderTop: "1px solid var(--line)", background: "var(--bg-2)" }}>
            <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{ display: "flex", gap: 8 }}>
              <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder={t.chat.placeholder}
                style={{
                  flex: 1,
                  background: "var(--bg-card)",
                  border: "1px solid var(--line)",
                  borderRadius: 10,
                  padding: "10px 12px",
                  color: "var(--text)",
                  fontSize: 14,
                  fontFamily: "inherit",
                  outline: "none",
                }}
              />
              <button type="submit" disabled={busy || !input.trim()} className="ta-btn ta-btn--accent" style={{ padding: "0 14px", opacity: busy || !input.trim() ? 0.5 : 1 }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
              </button>
            </form>
            <div style={{ color: "var(--text-3)", fontSize: 11, marginTop: 8, fontFamily: "var(--mono)" }}>{t.chat.hint}</div>
          </footer>
        </div>
      )}
    </>
  );
}

/* --------- Root App --------- */
function App() {
  const [t, lang, setLang] = useI18n();
  const TWEAKS = window.TA_TWEAKS;
  const tw = useTweakState(TWEAKS);
  const setTweakKeys = (edits) => window.parent.postMessage({ type: "__edit_mode_set_keys", edits }, "*");

  return (
    <div>
      <Nav t={t} lang={lang} setLang={setLang} theme={tw.theme} setTheme={tw.setTheme} />
      <Hero t={t} />
      <StatsStrip t={t} />
      <ProSection t={t} />
      <JournalSection t={t} />
      <CopierSection t={t} />
      <HowSection t={t} />
      <PricingSection t={t} />
      <ReviewsSection t={t} />
      <CTASection t={t} />
      <FAQSection t={t} />
      <Footer t={t} />
      <AIChatLauncher t={t} />
      <TweaksPanel t={t} {...tw} setTweakKeys={setTweakKeys} />
    </div>
  );
}

Object.assign(window, { Nav, Footer, AIChatLauncher, TweaksPanel, useTweakState, useI18n });

// Only mount if root is empty (i.e. on the home page).
// Product pages mount their own root with ProductPage component.
if (document.getElementById("root") && !window.__TA_PRODUCT_PAGE) {
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
}
