// ─────────────────────────────────────────────────────────────────────────
// pages.jsx — Home, Banks, Markets, Programs, Articles, FAQ, Contact, Privacy, Terms
// ─────────────────────────────────────────────────────────────────────────

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP } = React;

/* ═════════════════════════════════════════════════════════════
   HOME
   ═════════════════════════════════════════════════════════════ */
function HomePage({ country, navigate, lang, tweaks, tiles, visits = 0 }) {
  const t = window.I18N[lang]?.hero || window.I18N.pl.hero;
  const T = (k, fb) => window.t(lang, k, fb);
  return (
    <div>
      {/* Hero */}
      <section style={{ paddingTop: 48, paddingBottom: 32, position: "relative", overflow: "hidden" }}>
        <div style={{
          position: "absolute", top: -200, right: -200, width: 600, height: 600,
          background: "radial-gradient(closest-side, var(--accent-soft), transparent)",
          pointerEvents: "none", filter: "blur(40px)",
        }} />
        <div className="container">
          <div className="fade-up" style={{ maxWidth: 880 }}>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 20 }}>
              <span className="chip">
                <span className="live-dot" /> {t.kicker}
              </span>
              <VisitorChip visits={visits} lang={lang} />
            </div>
            <h1 style={{
              margin: 0,
              fontSize: "clamp(36px, 7vw, 80px)",
              fontWeight: 800, letterSpacing: "-0.035em",
              lineHeight: 1.0,
              textWrap: "balance",
            }}>
              {t.title1}<br />
              <span style={{
                background: "linear-gradient(95deg, var(--accent), oklch(0.85 0.14 60))",
                WebkitBackgroundClip: "text", backgroundClip: "text",
                WebkitTextFillColor: "transparent",
                fontStyle: "italic",
              }}>{t.title2}</span>
            </h1>
            <p style={{
              marginTop: 24,
              fontSize: "clamp(15px, 1.5vw, 19px)",
              color: "var(--text-2)",
              maxWidth: 640, lineHeight: 1.5,
            }}>
              {t.sub}
            </p>
            <div style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}>
              <button className="btn btn-primary" onClick={() => navigate("mortgage")} style={{ padding: "14px 22px", fontSize: 14 }}>
                {T("hero.mortgageBtn", "Mortgage Calculator")} <ArrowRight />
              </button>
              <button className="btn btn-ghost" onClick={() => navigate("banks")} style={{ padding: "14px 22px", fontSize: 14 }}>
                {T("hero.compareBtn", "Compare Banks")}
              </button>
            </div>

            {/* Stats row */}
            <div style={{ marginTop: 48, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))", gap: 24, maxWidth: 720 }}>
              <HeroStat value={String(window.COUNTRIES.length)} label={T("heroStats.countries", "EU Countries")} />
              <HeroStat value="100%" label={T("heroStats.free", "Free")} />
              <HeroStat value="AI" label={T("heroStats.aiAnalysis", "AI Analysis")} />
              <HeroStat value="Live" label={T("heroStats.liveFx", "Live FX")} />
            </div>
          </div>
        </div>
      </section>

      {/* Bento grid */}
      <section className="container" style={{ paddingTop: 24, paddingBottom: 48 }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(8, 1fr)",
          gap: 16,
        }} className="kr-bento">
          {tiles.map(tile => (
            <Tile key={tile.id} tile={tile} country={country} navigate={navigate} density={tweaks?.density} lang={lang} />
          ))}
        </div>
      </section>

      {/* Subtle ad break */}
      <section className="container" style={{ paddingBottom: 32 }}>
        <AdSlot size="leaderboard" label="Leaderboard 728×90" hint={window.t(lang, "common.betweenSections", "between sections")} />
      </section>

      {/* Why us */}
      <section className="container" style={{ paddingTop: 48, paddingBottom: 32 }}>
        <PageHeader kicker={T("whyUs.kicker", "Why KreditEU?")} title={T("whyUs.title", "Built for Europeans")}
          sub={T("whyUs.sub", "30 countries, government programs, AI analysis and live market data.")} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 16, marginTop: 16 }}>
          {(window.t(lang, "whyUs.features", []) || []).map((f, i) => (
            <div key={i} className="card card-hover" style={{ padding: 24 }}>
              <div style={{ fontSize: 28, marginBottom: 14 }}>{f[0]}</div>
              <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800, letterSpacing: "-0.01em" }}>{f[1]}</h3>
              <p style={{ marginTop: 8, fontSize: 13, color: "var(--text-2)", lineHeight: 1.6 }}>{f[2]}</p>
            </div>
          ))}
        </div>
      </section>

      {/* CTA strip */}
      <section className="container" style={{ paddingTop: 48 }}>
        <div className="card" style={{
          padding: "clamp(32px, 5vw, 56px)",
          background: "linear-gradient(135deg, var(--accent-soft), transparent), var(--surface)",
          border: "1px solid var(--accent)",
          textAlign: "center",
          position: "relative", overflow: "hidden",
        }}>
          <h2 style={{ margin: 0, fontSize: "clamp(24px, 3.5vw, 38px)", fontWeight: 800, letterSpacing: "-0.02em" }}>
            {T("ctaStrip.title", "Ready to calculate?")}
          </h2>
          <p style={{ marginTop: 12, fontSize: 15, color: "var(--text-2)", maxWidth: 520, margin: "12px auto 0" }}>
            {T("ctaStrip.sub", "Choose your loan type and compare offers from 15+ banks in under a minute.")}
          </p>
          <div style={{ marginTop: 24, display: "inline-flex", gap: 12, flexWrap: "wrap", justifyContent: "center" }}>
            <button className="btn btn-primary" onClick={() => navigate("mortgage")} style={{ padding: "14px 22px" }}>{T("ctaStrip.mortgage", "🏠 Mortgage")}</button>
            <button className="btn btn-soft" onClick={() => navigate("cash")} style={{ padding: "14px 22px" }}>{T("ctaStrip.cash", "💳 Cash Loan")}</button>
          </div>
        </div>
      </section>
    </div>
  );
}

function HeroStat({ value, label }) {
  return (
    <div>
      <div style={{ fontSize: "clamp(24px, 3vw, 36px)", fontWeight: 800, letterSpacing: "-0.02em", color: "var(--accent)" }}>{value}</div>
      <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.08em", marginTop: 4 }}>{label}</div>
    </div>
  );
}

/* ═════════════════════════════════════════════════════════════
   MORTGAGE / CASH page
   ═════════════════════════════════════════════════════════════ */
function CalcPage({ kind, country, navigate, lang }) {
  const isMortgage = kind === "mortgage";
  const prefix = isMortgage ? "pages.mortgage" : "pages.cash";
  const labels = {
    kicker: window.t(lang, `${prefix}.kicker`, isMortgage ? "🏠 Mortgage" : "💳 Cash Loan"),
    title: window.t(lang, `${prefix}.title`, isMortgage ? "Mortgage Calculator" : "Cash Loan Calculator"),
    sub: window.t(lang, `${prefix}.sub`, isMortgage ? "Enter your parameters and compare bank offers." : "Check your monthly payment with total cost."),
  };
  const tips = window.t(lang, `${prefix}.tips`, [
    ["Check creditworthiness", "Estimate your approval probability first."],
    ["Compare offers", "A 0.5% difference can save a lot over time."],
    ["APR matters", "APR reflects the true total cost of borrowing."],
    ["Currency risk", "FX movement can change your monthly payment."],
  ]);
  return (
    <div className="container">
      <Breadcrumbs items={[
        { label: window.t(lang, "common.home", "Home"), route: "home" },
        { label: labels.title },
      ]} navigate={navigate} />
      <PageHeader {...labels} />
      <FullCalculator country={country} mode={kind} navigate={navigate} lang={lang} />

      <div style={{ marginTop: 48 }}>
        <AdSlot size="leaderboard" hint={window.t(lang, "common.betweenSectionsAd", "728x90 between sections")} />
      </div>

      <PageHeader
        kicker={window.t(lang, `${prefix}.tipsKicker`, "Tips")}
        title={window.t(lang, `${prefix}.tipsTitle`, "Before you sign")}
        sub={window.t(lang, `${prefix}.tipsSub`, "4 simple rules to reduce total cost.")}
      />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 16, marginBottom: 32 }}>
        {tips.map(([i, t, b], k) => (
          <div key={k} className="card" style={{ padding: 20 }}>
            <div style={{ fontSize: 24, marginBottom: 8 }}>{i}</div>
            <h4 style={{ margin: 0, fontSize: 14, fontWeight: 800 }}>{t}</h4>
            <p style={{ marginTop: 6, fontSize: 12, color: "var(--text-2)", lineHeight: 1.5 }}>{b}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════════════════════
   BANKS RANKING
   ═════════════════════════════════════════════════════════════ */
function BanksPage({ country, navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.banks.${k}`, fb);
  const [filter, setFilter] = useStateP("all");
  const [sort, setSort] = useStateP("mortgage");

  const filtered = window.BANKS.filter(b => {
    if (filter === "all") return true;
    return b.country === filter;
  });
  const sorted = [...filtered].sort((a, b) => a[sort] - b[sort]);

  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: T("crumb", "Banks") }]} navigate={navigate} />
      <PageHeader kicker={T("kicker", "🏦 Current Rates")}
        title={T("title", "Compare Bank Rates")}
        sub={T("sub", "Current mortgage and cash loan rates in 30 European countries.")} />

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12, marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {[["all", `🌍 ${window.t(lang, "common.all", "All")}`], ["pl", "🇵🇱 PL"], ["de", "🇩🇪 DE"], ["fr", "🇫🇷 FR"], ["cz", "🇨🇿 CZ"]].map(([k, l]) => (
            <button key={k} onClick={() => setFilter(k)} style={{
              padding: "8px 14px",
              background: filter === k ? "var(--accent)" : "var(--surface)",
              color: filter === k ? "var(--bg)" : "var(--text-2)",
              border: "1px solid " + (filter === k ? "var(--accent)" : "var(--border-soft)"),
              borderRadius: 999, fontSize: 12, fontWeight: 700, cursor: "pointer",
              transition: "all 0.14s",
            }}>{l}</button>
          ))}
        </div>
        <span style={{ fontSize: 11, color: "var(--text-3)" }}>{T("lastUpdate", "Last update: 2026-05-12")}</span>
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 760 }}>
            <thead>
              <tr style={{ background: "var(--bg-2)", borderBottom: "1px solid var(--border)" }}>
                <th style={th()}>#</th>
                <th style={th("left")}>{T("th.bank", "Bank")}</th>
                <th style={th()}>{T("th.country", "Country")}</th>
                <SortTh active={sort === "mortgage"} onClick={() => setSort("mortgage")}>{T("th.mortgage", "Mortgage")}</SortTh>
                <SortTh active={sort === "cash"} onClick={() => setSort("cash")}>{T("th.cash", "Cash")}</SortTh>
                <th style={th()}>{T("th.rrso", "APR")}</th>
                <th style={th()}>{T("th.maxLtv", "Max LTV")}</th>
                <th style={th()}>{T("th.prov", "Fee")}</th>
                <th style={th()}>{T("th.trend", "Trend")}</th>
              </tr>
            </thead>
            <tbody>
              {sorted.map((b, i) => {
                const c = window.COUNTRIES.find(c => c.code === b.country);
                return (
                  <tr key={b.id} style={{ borderTop: "1px solid var(--border-soft)" }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <td style={td()}>
                      <span style={{
                        width: 22, height: 22, borderRadius: 6,
                        background: i < 3 ? "var(--accent)" : "var(--surface-2)",
                        color: i < 3 ? "var(--bg)" : "var(--text-2)",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        fontSize: 11, fontWeight: 800,
                      }}>{i + 1}</span>
                    </td>
                    <td style={td("left")}><strong style={{ color: "var(--text)" }}>{b.name}</strong></td>
                    <td style={td()}><span style={{ fontSize: 18 }}>{c?.flag}</span></td>
                    <td style={td()}><span className="num-mono" style={{ fontWeight: 700, color: i === 0 ? "var(--accent)" : "var(--text)" }}>{b.mortgage.toFixed(2)}%</span></td>
                    <td style={td()}><span className="num-mono">{b.cash.toFixed(2)}%</span></td>
                    <td style={td()}><span className="num-mono">{b.rrso.toFixed(2)}%</span></td>
                    <td style={td()}><span className="num-mono">{b.ltv}%</span></td>
                    <td style={td()}><span className="num-mono">{b.prov.toFixed(1)}%</span></td>
                    <td style={td()}>
                      <TrendPill value={b.trend} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <p style={{ fontSize: 11, color: "var(--text-3)", marginTop: 16 }}>
        {T("disclaimer", "* Indicative data only. Final rate depends on individual credit assessment.")}
      </p>

      <div style={{ marginTop: 32 }}>
        <AdSlot size="leaderboard" hint="728×90" />
      </div>

      <InternalLinksCard
        title={window.t(lang, "common.relatedTools", "Related tools")}
        lang={lang}
        navigate={navigate}
        links={[
          { label: window.t(lang, "calc.typeMortgage", "Mortgage Calculator"), route: "mortgage" },
          { label: window.t(lang, "calc.typeCash", "Cash Loan Calculator"), route: "cash" },
          { label: window.t(lang, "nav.markets", "Markets"), route: "markets" },
          { label: window.t(lang, "nav.articles", "Articles"), route: "articles" },
        ]}
      />
    </div>
  );
}

function th(align = "center") {
  return {
    padding: "14px 12px", textAlign: align,
    fontSize: 10, fontWeight: 800, color: "var(--text-3)",
    textTransform: "uppercase", letterSpacing: "0.08em",
  };
}
function td(align = "center") {
  return { padding: "14px 12px", textAlign: align, fontSize: 13, color: "var(--text-2)" };
}
function SortTh({ active, onClick, children }) {
  return (
    <th style={{ ...th(), cursor: "pointer", color: active ? "var(--accent)" : "var(--text-3)" }} onClick={onClick}>
      {children} {active ? "↓" : ""}
    </th>
  );
}

/* ═════════════════════════════════════════════════════════════
   MARKETS
   ═════════════════════════════════════════════════════════════ */
function MarketsPage({ navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.markets.${k}`, fb);
  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: T("crumb", "Markets") }]} navigate={navigate} />
      <PageHeader kicker={T("kicker", "📊 Market Data")} title={T("title", "Reference Indicators")}
        sub={T("sub", "WIBOR, EURIBOR and FX rates relevant for loans.")} />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 16 }}>
        {window.REFERENCE_RATES.map(r => (
          <div key={r.code} className="card card-hover" style={{ padding: 20 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{r.name}</div>
                <div className="num-mono" style={{ fontSize: 32, fontWeight: 800, letterSpacing: "-0.02em", marginTop: 4 }}>
                  {r.value.toFixed(2)}<span style={{ fontSize: 16, color: "var(--text-3)" }}>%</span>
                </div>
                <TrendPill value={r.change} />
              </div>
              <Sparkline data={r.trend} width={100} height={36} />
            </div>
          </div>
        ))}
      </div>

      <PageHeader title={T("fxTitle", "FX Rates (NBP / ECB)")} sub={T("fxNote", "Update: 2026-05-12 · 10:00")} />

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ background: "var(--bg-2)" }}>
              <th style={th("left")}>{window.t(lang, "common.fxPair", "FX Pair")}</th>
              <th style={th()}>{window.t(lang, "common.rate", "Rate")}</th>
              <th style={th()}>24h</th>
              <th style={th()}>7d</th>
              <th style={th()}>{window.t(lang, "common.source", "Source")}</th>
            </tr>
          </thead>
          <tbody>
            {window.FX.map(fx => (
              <tr key={fx.pair} style={{ borderTop: "1px solid var(--border-soft)" }}>
                <td style={td("left")}><strong>{fx.pair}</strong></td>
                <td style={td()}><span className="num-mono" style={{ fontWeight: 700 }}>{fx.value.toFixed(4)}</span></td>
                <td style={td()}><TrendPill value={fx.d24} /></td>
                <td style={td()}><TrendPill value={fx.d7} /></td>
                <td style={td()}><span style={{ fontSize: 11, color: "var(--text-3)" }}>{fx.source}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p style={{ fontSize: 11, color: "var(--text-3)", marginTop: 16 }}>
        {T("ratesNote", "Indicative values. Source: NBP / ECB.")}
      </p>

      <div style={{ marginTop: 32 }}>
        <AdSlot size="leaderboard" hint="728×90" />
      </div>

      <InternalLinksCard
        title={window.t(lang, "common.relatedTools", "Related tools")}
        lang={lang}
        navigate={navigate}
        links={[
          { label: window.t(lang, "nav.banks", "Banks"), route: "banks" },
          { label: window.t(lang, "calc.typeMortgage", "Mortgage Calculator"), route: "mortgage" },
          { label: window.t(lang, "nav.programs", "Programs"), route: "programs" },
          { label: window.t(lang, "nav.articles", "Articles"), route: "articles" },
        ]}
      />
    </div>
  );
}

/* ═════════════════════════════════════════════════════════════
   PROGRAMS
   ═════════════════════════════════════════════════════════════ */
function ProgramsPage({ navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.programs.${k}`, fb);
  const programs = (window.getLocalizedPrograms && window.getLocalizedPrograms(lang)) || window.PROGRAMS;
  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: T("crumb", "Programs") }]} navigate={navigate} />
      <PageHeader kicker={T("kicker", "🏛️ Programs")}
        title={T("title", "Government Housing Support")}
        sub={T("sub", "Subsidy and preferential loan programs available in Europe.")} />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16 }}>
        {programs.map(p => {
          const c = window.COUNTRIES.find(c => c.code === p.country);
          return (
            <div key={p.id} className="card card-hover" style={{ padding: 24 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                <div style={{ fontSize: 28 }}>{p.icon}</div>
                <span className="chip">{c?.flag} {c?.name}</span>
              </div>
              <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: "-0.01em" }}>{p.name}</h3>
              <p style={{ marginTop: 8, fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>{p.short}</p>
              <div style={{ marginTop: 16, padding: 14, background: "var(--accent-soft)", borderRadius: 10, border: "1px solid var(--accent)" }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: 4 }}>{T("benefit", "Benefit")}</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text)" }}>{p.benefit}</div>
              </div>
              <div style={{ marginTop: 12, fontSize: 11, color: "var(--text-3)" }}>
                <strong style={{ color: "var(--text-2)" }}>{T("whoCan", "Who can apply?")}</strong> {p.eligible}
              </div>
            </div>
          );
        })}
      </div>

      <InternalLinksCard
        title={window.t(lang, "common.relatedTools", "Related tools")}
        lang={lang}
        navigate={navigate}
        links={[
          { label: window.t(lang, "calc.typeMortgage", "Mortgage Calculator"), route: "mortgage" },
          { label: window.t(lang, "nav.banks", "Banks"), route: "banks" },
          { label: window.t(lang, "nav.markets", "Markets"), route: "markets" },
          { label: window.t(lang, "nav.faq", "FAQ"), route: "faq" },
        ]}
      />
    </div>
  );
}

/* ═════════════════════════════════════════════════════════════
   ARTICLES list + Article view
   ═════════════════════════════════════════════════════════════ */
function ArticlesPage({ navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.articles.${k}`, fb);
  const localizedArticles = (window.getLocalizedArticles && window.getLocalizedArticles(lang)) || window.ARTICLES;
  const [cat, setCat] = useStateP("all");
  const cats = ["all", ...new Set(localizedArticles.map(a => a.cat))];
  const list = cat === "all" ? localizedArticles : localizedArticles.filter(a => a.cat === cat);
  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: T("crumb", "Articles") }]} navigate={navigate} />
      <PageHeader kicker={T("kicker", "📚 Knowledge Base")} title={T("title", "Loan Guides")}
        sub={T("sub", "Practical content that helps you make better financial decisions.")} />

      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 24 }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)} style={{
            padding: "8px 14px",
            background: cat === c ? "var(--accent)" : "var(--surface)",
            color: cat === c ? "var(--bg)" : "var(--text-2)",
            border: "1px solid " + (cat === c ? "var(--accent)" : "var(--border-soft)"),
            borderRadius: 999, fontSize: 12, fontWeight: 700, cursor: "pointer",
          }}>{c === "all" ? T("catAll", "All") : c}</button>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 20 }}>
        {list.map(a => (
          <button key={a.id} onClick={() => navigate({ name: "article", id: a.id })} style={{
            padding: 0, background: "transparent", border: "none", cursor: "pointer", textAlign: "left",
          }}>
            <div className="card card-hover" style={{ padding: 0, overflow: "hidden", height: "100%" }}>
              <div style={{ width: "100%", aspectRatio: "16/9", background: a.img, position: "relative" }}>
                <span style={{
                  position: "absolute", top: 12, left: 12,
                  padding: "4px 10px", background: "rgba(0,0,0,0.6)", color: "white", borderRadius: 999,
                  fontSize: 10, fontWeight: 700, backdropFilter: "blur(8px)",
                }}>{a.tag}</span>
              </div>
              <div style={{ padding: 20 }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: "var(--accent)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>{a.cat}</div>
                <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: "-0.01em", lineHeight: 1.25 }}>{a.title}</h3>
                <p style={{ marginTop: 10, fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>{a.excerpt}</p>
                <div style={{ marginTop: 16, display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--text-3)" }}>
                  <span>{a.date}</span>
                  <span>{a.read} {window.t(lang, "common.minutes", "min read")}</span>
                </div>
              </div>
            </div>
          </button>
        ))}
      </div>

      <InternalLinksCard
        title={window.t(lang, "common.relatedTools", "Related tools")}
        lang={lang}
        navigate={navigate}
        links={[
          { label: window.t(lang, "calc.typeMortgage", "Mortgage Calculator"), route: "mortgage" },
          { label: window.t(lang, "nav.banks", "Banks"), route: "banks" },
          { label: window.t(lang, "nav.markets", "Markets"), route: "markets" },
          { label: window.t(lang, "nav.contact", "Contact"), route: "contact" },
        ]}
      />
    </div>
  );
}

function getArticleBodyCopy(lang) {
  const copy = {
    en: {
      takeaways: [
        "Current WIBOR 3M is at 5.86%, the lowest level since 2022.",
        "Average mortgage rate: 6.80% in PL vs 3.85% in the euro area.",
        "A ~3pp spread can mean roughly 2,000 PLN/month difference on a 400k loan.",
        "FX risk is real: a 10% PLN weakening can increase EUR-loan installments.",
      ],
      recent:
        "The ECB cut its deposit rate by 25 bps in March and EURIBOR 3M dropped below 2.7%. European banks quickly reflected that in pricing. NBP kept rates at 5.75%, while markets still price cuts in the second half of 2026.",
      quote:
        "If you plan a loan in 2026, timing matters. Waiting a quarter for lower benchmarks can reduce your starting rate by 0.3–0.5pp.",
      action:
        "If you already have a loan, check whether recalculation now improves your payment path. If you are applying soon, compare at least 5 offers using the calculator.",
    },
    pl: {
      takeaways: [
        "Aktualna stopa WIBOR 3M to 5.86%, najniĹĽej od 2022 r.",
        "Ĺšrednie oprocentowanie hipoteczne: 6.80% w PL vs 3.85% w strefie euro.",
        "Różnica ~3 pp. może oznaczać około 2 000 PLN/mies. przy kredycie 400k.",
        "Ryzyko walutowe pozostaje realne: 10% osłabienia PLN podnosi ratę kredytu w EUR.",
      ],
      recent:
        "EBC obniżył stopę depozytową o 25 pb. w marcu, a EURIBOR 3M spadł poniżej 2.7%. Banki szybko odzwierciedliły to w cennikach. NBP utrzymał stopy na 5.75%, choć rynek nadal wycenia obniżki w drugiej połowie 2026.",
      quote:
        "Jeśli planujesz kredyt w 2026 r., timing ma znaczenie. Czekanie kwartał na niższe stopy bazowe może obniżyć stawkę startową o 0.3–0.5 pp.",
      action:
        "Jeśli masz już kredyt, sprawdź czy przeliczenie poprawi ratę. Jeśli składasz nowy wniosek, porównaj minimum 5 ofert w kalkulatorze.",
    },
    de: {
      takeaways: [
        "Der aktuelle WIBOR 3M liegt bei 5,86% und ist damit auf dem niedrigsten Stand seit 2022.",
        "Durchschnittlicher Hypothekenzins: 6,80% in Polen vs. 3,85% im Euroraum.",
        "Ein Spread von ~3 Prozentpunkten kann bei 400k Kredit rund 2.000 PLN/Monat bedeuten.",
        "Währungsrisiko bleibt relevant: 10% schwächerer PLN erhöht EUR-Raten spürbar.",
      ],
      recent:
        "Die EZB senkte im März den Einlagensatz um 25 Basispunkte, EURIBOR 3M fiel unter 2,7%. Europäische Banken passten ihre Konditionen schnell an. Die NBP hielt 5,75%, der Markt preist dennoch Senkungen im zweiten Halbjahr 2026 ein.",
      quote:
        "Wenn Sie 2026 finanzieren wollen, ist das Timing entscheidend. Ein Quartal warten kann den Startzins um 0,3–0,5 Prozentpunkte senken.",
      action:
        "Bei bestehendem Kredit lohnt sich eine Neuberechnung. Bei neuer Finanzierung sollten mindestens 5 Angebote verglichen werden.",
    },
    fr: {
      takeaways: [
        "Le WIBOR 3M est à 5,86%, son plus bas niveau depuis 2022.",
        "Taux hypothécaire moyen: 6,80% en Pologne contre 3,85% en zone euro.",
        "Un écart d'environ 3 points peut représenter ~2 000 PLN/mois sur 400k.",
        "Le risque de change reste réel: -10% du PLN augmente la mensualité d'un prêt en EUR.",
      ],
      recent:
        "La BCE a abaissé son taux de dépôt de 25 pdb en mars et l'EURIBOR 3M est passé sous 2,7%. Les banques européennes ont ajusté leurs barèmes rapidement. La NBP reste à 5,75%, mais le marché anticipe encore des baisses au second semestre 2026.",
      quote:
        "Si vous préparez un crédit en 2026, le timing est clé. Attendre un trimestre peut réduire le taux de départ de 0,3 à 0,5 point.",
      action:
        "Si vous avez déjà un prêt, vérifiez l'intérêt d'un recalcul. Pour une nouvelle demande, comparez au moins 5 offres.",
    },
    cs: {
      takeaways: [
        "Aktuální WIBOR 3M je 5,86 %, nejníže od roku 2022.",
        "Průměrná hypotéka: 6,80 % v PL vs 3,85 % v eurozóně.",
        "Rozdíl ~3 p.b. může u úvěru 400k znamenat cca 2 000 PLN měsíčně.",
        "Kurzové riziko je reálné: oslabení PLN o 10 % zvyšuje splátku úvěru v EUR.",
      ],
      recent:
        "ECB v březnu snížila depozitní sazbu o 25 bb a EURIBOR 3M klesl pod 2,7 %. Evropské banky to rychle promítly do sazeb. NBP drží 5,75 %, trh však stále očekává snížení ve druhé polovině 2026.",
      quote:
        "Pokud plánujete úvěr v roce 2026, načasování je zásadní. Čekání jedno čtvrtletí může snížit startovní sazbu o 0,3–0,5 p.b.",
      action:
        "U stávajícího úvěru zvažte přepočet. U nové žádosti porovnejte alespoň 5 nabídek.",
    },
    hu: {
      takeaways: [
        "A WIBOR 3M jelenleg 5,86%, ami 2022 óta a legalacsonyabb.",
        "Átlagos jelzálogkamat: 6,80% Lengyelországban vs 3,85% az eurózónában.",
        "Kb. 3 százalékpontos különbség 400k hitelnél ~2 000 PLN/hó eltérést jelenthet.",
        "Az árfolyamkockázat valós: 10% PLN-gyengülés növeli az EUR-hitel törlesztőjét.",
      ],
      recent:
        "Az EKB márciusban 25 bázisponttal csökkentette a betéti rátát, az EURIBOR 3M 2,7% alá esett. Az európai bankok gyorsan átáraztak. Az NBP 5,75%-on tart, de a piac 2026 második felére további vágást vár.",
      quote:
        "Ha 2026-ban hitelt tervezel, az időzítés kulcsfontosságú. Egy negyedév várakozás 0,3–0,5 százalékponttal alacsonyabb induló kamatot hozhat.",
      action:
        "Meglévő hitelnél érdemes újraszámolni. Új hitelnél legalább 5 ajánlatot hasonlíts össze.",
    },
    nl: {
      takeaways: [
        "WIBOR 3M staat op 5,86%, het laagste niveau sinds 2022.",
        "Gemiddelde hypotheekrente: 6,80% in PL tegenover 3,85% in de eurozone.",
        "Een spread van ~3 procentpunt kan bij 400k circa 2.000 PLN/maand schelen.",
        "Valutarisico blijft reëel: 10% zwakkere PLN verhoogt EUR-leninglasten.",
      ],
      recent:
        "De ECB verlaagde in maart de depositorente met 25 bp en EURIBOR 3M dook onder 2,7%. Europese banken verwerkten dat snel in prijzen. NBP bleef op 5,75%, terwijl de markt nog steeds verlagingen voor H2 2026 inprijst.",
      quote:
        "Als je in 2026 financiert, is timing belangrijk. Een kwartaal wachten kan de startmarge met 0,3–0,5 procentpunt verlagen.",
      action:
        "Heb je al een lening, herbereken dan je scenario. Voor een nieuwe aanvraag: vergelijk minstens 5 aanbiedingen.",
    },
  };
  return copy[lang] || copy.en;
}

function PublicArticleMarkdown({ body }) {
  const blocks = String(body || "").split(/\n{2,}/).filter(Boolean);
  return (
    <>
      {blocks.map((block, idx) => {
        const trimmed = block.trim();
        if (trimmed.startsWith("## ")) {
          return <h2 key={idx} style={h2Style()}>{trimmed.slice(3)}</h2>;
        }
        if (trimmed.startsWith("- ")) {
          return (
            <ul key={idx} style={ulStyle()}>
              {trimmed.split(/\n/).map((line, i) => <li key={i}>{line.replace(/^-\s*/, "")}</li>)}
            </ul>
          );
        }
        return <p key={idx}>{trimmed}</p>;
      })}
    </>
  );
}

function ArticlePage({ id, navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.article.${k}`, fb);
  const bodyCopy = getArticleBodyCopy(lang);
  const localizedArticles = (window.getLocalizedArticles && window.getLocalizedArticles(lang)) || window.ARTICLES;
  const a = localizedArticles.find(x => x.id === id) || localizedArticles[0];
  return (
    <div className="container">
      <Breadcrumbs items={[
        { label: window.t(lang, "common.home", "Home"), route: "home" },
        { label: window.t(lang, "pages.articles.crumb", "Articles"), route: "articles" },
        { label: a.cat },
      ]} navigate={navigate} />

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 720px) minmax(220px, 280px)", gap: 48, marginTop: 16 }} className="kr-article-grid">
        <article>
          <span className="chip" style={{ marginBottom: 16 }}>{a.cat}</span>
          <h1 style={{ margin: 0, fontSize: "clamp(28px, 4vw, 44px)", fontWeight: 800, letterSpacing: "-0.025em", lineHeight: 1.15, textWrap: "balance" }}>
            {a.title}
          </h1>
          <div style={{ marginTop: 16, display: "flex", gap: 16, fontSize: 12, color: "var(--text-3)" }}>
            <span>{a.author}</span>
            <span>·</span>
            <span>{a.date}</span>
            <span>·</span>
            <span>{a.read} {window.t(lang, "common.minutes", "min read")}</span>
          </div>
          <div style={{ marginTop: 24, width: "100%", aspectRatio: "16/9", background: a.img, borderRadius: 14 }} />

          <div style={{ marginTop: 32, fontSize: 16, lineHeight: 1.7, color: "var(--text)" }}>
            <p style={{ fontSize: 18, fontWeight: 500, color: "var(--text-2)" }}>{a.excerpt}</p>
            {a.body ? (
              <PublicArticleMarkdown body={a.body} />
            ) : (
              <>
                <h2 style={h2Style()}>{window.t(lang, "article.content.keyTakeaways", "Key takeaways")}</h2>
                <ul style={ulStyle()}>
                  {bodyCopy.takeaways.map((point, idx) => <li key={idx}>{point}</li>)}
                </ul>

                <h2 style={h2Style()}>{window.t(lang, "article.content.recentMonths", "What changed recently")}</h2>
                <p>{bodyCopy.recent}</p>

                <blockquote style={blockquoteStyle()}>
                  "{bodyCopy.quote}"
                </blockquote>

                <h2 style={h2Style()}>{window.t(lang, "article.content.whatYouCanDo", "What you can do")}</h2>
                <p>{bodyCopy.action}</p>
              </>
            )}

            <div style={{ marginTop: 32, padding: 24, background: "var(--accent-soft)", borderRadius: 14, border: "1px solid var(--accent)" }}>
              <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>{T("calcCard", "📊 Calculate now")}</h3>
              <p style={{ marginTop: 6, fontSize: 13, color: "var(--text-2)" }}>{T("calcCardSub", "Check potential savings with your own numbers.")}</p>
              <button className="btn btn-primary" onClick={() => navigate("mortgage")} style={{ marginTop: 12 }}>{T("readMore", "Open calculator")} <ArrowRight /></button>
            </div>

            <InternalLinksCard
              title={window.t(lang, "common.relatedGuides", "Related guides")}
              lang={lang}
              navigate={navigate}
              links={[
                { label: window.t(lang, "nav.articles", "All articles"), route: "articles" },
                { label: window.t(lang, "nav.banks", "Compare banks"), route: "banks" },
                { label: window.t(lang, "nav.markets", "Market indicators"), route: "markets" },
                { label: window.t(lang, "nav.programs", "Government programs"), route: "programs" },
              ]}
            />
          </div>
        </article>

        <aside style={{ position: "sticky", top: 100, alignSelf: "flex-start" }} className="kr-article-aside">
          <AdSlot size="sidebar" hint="300×600 sticky" />
          <div className="card" style={{ padding: 18, marginTop: 16 }}>
            <h4 style={{ margin: 0, fontSize: 11, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--text-3)" }}>{T("recommended", "Recommended")}</h4>
            <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 12 }}>
              {localizedArticles.filter(x => x.id !== a.id).slice(0, 3).map(r => (
                <button key={r.id} onClick={() => navigate({ name: "article", id: r.id })} style={{
                  background: "transparent", border: "none", padding: 0, textAlign: "left", cursor: "pointer",
                }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text)", lineHeight: 1.3 }}>{r.title}</div>
                  <div style={{ fontSize: 10, color: "var(--text-3)", marginTop: 2 }}>{r.read} {window.t(lang, "common.minutes", "min read")}</div>
                </button>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function h2Style() { return { marginTop: 32, marginBottom: 16, fontSize: 22, fontWeight: 800, letterSpacing: "-0.015em" }; }
function ulStyle() { return { marginTop: 12, paddingLeft: 20, lineHeight: 1.8, color: "var(--text-2)" }; }
function blockquoteStyle() {
  return {
    margin: "24px 0",
    padding: "16px 20px",
    borderLeft: "3px solid var(--accent)",
    background: "var(--bg-2)",
    fontStyle: "italic",
    fontSize: 16,
    color: "var(--text)",
    borderRadius: "0 12px 12px 0",
  };
}

/* ═════════════════════════════════════════════════════════════
   FAQ
   ═════════════════════════════════════════════════════════════ */
function FaqPage({ navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.faq.${k}`, fb);
  const localizedFaqs = (window.getLocalizedFaqs && window.getLocalizedFaqs(lang)) || window.FAQS;
  const [open, setOpen] = useStateP(null);
  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: T("crumb", "FAQ") }]} navigate={navigate} />
      <PageHeader kicker={T("kicker", "❓ FAQ")} title={T("title", "Have questions?")}
        sub={T("sub", "Everything about calculator logic, rates and loan assumptions.")} />
      <div style={{ display: "flex", flexDirection: "column", gap: 8, maxWidth: 800 }}>
        {localizedFaqs.map((f, i) => (
          <div key={i} className="card" style={{ padding: 0, overflow: "hidden" }}>
            <button onClick={() => setOpen(open === i ? null : i)} style={{
              width: "100%", padding: "18px 22px",
              background: "transparent", border: "none",
              display: "flex", justifyContent: "space-between", alignItems: "center",
              cursor: "pointer", textAlign: "left",
              fontSize: 15, fontWeight: 700, color: "var(--text)",
            }}>
              <span>{f.q}</span>
              <span style={{ color: "var(--accent)", fontSize: 22, transform: open === i ? "rotate(45deg)" : "none", transition: "transform 0.2s" }}>+</span>
            </button>
            {open === i && (
              <div style={{ padding: "0 22px 22px", fontSize: 14, color: "var(--text-2)", lineHeight: 1.6 }}>
                {f.a}
              </div>
            )}
          </div>
        ))}
      </div>

      <InternalLinksCard
        title={window.t(lang, "common.relatedTools", "Related tools")}
        lang={lang}
        navigate={navigate}
        links={[
          { label: window.t(lang, "calc.typeMortgage", "Mortgage Calculator"), route: "mortgage" },
          { label: window.t(lang, "calc.typeCash", "Cash Loan Calculator"), route: "cash" },
          { label: window.t(lang, "nav.articles", "Articles"), route: "articles" },
          { label: window.t(lang, "nav.contact", "Contact"), route: "contact" },
        ]}
      />
    </div>
  );
}

/* ═════════════════════════════════════════════════════════════
   CONTACT
   ═════════════════════════════════════════════════════════════ */
function ContactPage({ navigate, lang }) {
  const T = (k, fb) => window.t(lang, `pages.contact.${k}`, fb);
  const topicLabels = window.t(lang, "pages.contact.topics", {
    general: "General question",
    bug: "Bug report",
    ads: "Advertising / partnership",
    rodo: "Data deletion (GDPR)",
  });
  const [form, setForm] = useStateP({ name: "", email: "", topic: "general", msg: "" });
  const [sent, setSent] = useStateP(false);
  const submit = (e) => {
    e.preventDefault();
    // Save to internal inbox (localStorage)
    try {
      const inbox = JSON.parse(localStorage.getItem("kr_inbox") || "[]");
      inbox.unshift({
        id: Date.now(),
        name: form.name, email: form.email, topic: form.topic, msg: form.msg,
        date: new Date().toISOString(),
        status: "new",
      });
      localStorage.setItem("kr_inbox", JSON.stringify(inbox));
    } catch (err) {}
    setSent(true);
  };
  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: T("crumb", "Contact") }]} navigate={navigate} />
      <PageHeader kicker={T("kicker", "📬 Contact")} title={T("title", "Need help? Write to us.")}
        sub={T("sub", "We usually respond within 24-48h.")} />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }} className="kr-contact-grid">
        <div className="card" style={{ padding: 28 }}>
          {sent ? (
            <div style={{ textAlign: "center", padding: "40px 0" }}>
              <div style={{ fontSize: 48, marginBottom: 16 }}>âś…</div>
              <h3 style={{ margin: 0, fontSize: 22, fontWeight: 800 }}>{T("sent", "Message sent!")}</h3>
              <p style={{ marginTop: 8, color: "var(--text-2)" }}>{T("sentSub", "Your message reached our internal inbox.")}</p>
            </div>
          ) : (
            <form onSubmit={submit}>
              <Field label={T("name", "Name")}>
                <input className="input" required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
              </Field>
              <div style={{ height: 16 }} />
              <Field label={T("email", "Email")}>
                <input className="input" required type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
              </Field>
              <div style={{ height: 16 }} />
              <Field label={T("topic", "Topic")}>
                <select className="select" value={form.topic} onChange={e => setForm({ ...form, topic: e.target.value })}>
                  <option value="general">{topicLabels.general}</option>
                  <option value="bug">{topicLabels.bug}</option>
                  <option value="ads">{topicLabels.ads}</option>
                  <option value="rodo">{topicLabels.rodo}</option>
                </select>
              </Field>
              <div style={{ height: 16 }} />
              <Field label={T("message", "Message")}>
                <textarea className="input" required rows={5} value={form.msg} onChange={e => setForm({ ...form, msg: e.target.value })}
                  style={{ resize: "vertical", minHeight: 120 }} />
              </Field>
              <button type="submit" className="btn btn-primary" style={{ marginTop: 20, width: "100%", justifyContent: "center" }}>
                {T("send", "📤 Send")}
              </button>
            </form>
          )}
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card" style={{ padding: 24, background: "linear-gradient(155deg, var(--accent-soft), transparent 70%), var(--surface)", border: "1px solid var(--accent)" }}>
            <div style={{ fontSize: 28, marginBottom: 8 }}>📬</div>
            <h4 style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>{window.t(lang, "pages.contact.inboxTitle", "KreditEU Internal Inbox")}</h4>
            <p style={{ marginTop: 6, fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>
              {T("emailSub", "Messages from this form are routed directly to our internal inbox.")}
            </p>
            <div style={{ marginTop: 12, padding: "8px 12px", background: "var(--bg-2)", borderRadius: 8, fontSize: 12, fontFamily: "var(--font-mono)", color: "var(--accent)" }}>
              kontakt@krediteu.com
            </div>
          </div>

          <div className="card" style={{ padding: 20 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 12 }}>
              {window.t(lang, "common.formTopics", "Form Topics")}
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {[
                ["📬", topicLabels.general, T("emailSub", "Response in 24-48h")],
                ["🐛", topicLabels.bug, T("bugSub", "Technical verification and follow-up")],
                ["💼", topicLabels.ads, T("adsSub", "Partnership details sent within 48h")],
                ["🔒", topicLabels.rodo, window.t(lang, "common.rodoSla", "Handled under GDPR time limits")],
              ].map(([i, t, s], k) => (
                <div key={k} style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                  <span style={{ fontSize: 18 }}>{i}</span>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 700 }}>{t}</div>
                    <div style={{ fontSize: 11, color: "var(--text-3)" }}>{s}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ padding: 14, background: "var(--bg-2)", borderRadius: 10, border: "1px solid var(--border-soft)", fontSize: 11, color: "var(--text-3)", lineHeight: 1.6 }}>
            {window.t(lang, "common.contactPrivacyNote", "🛡️ Your message is handled securely and processed under our privacy policy.")}
          </div>
        </div>
      </div>

      <InternalLinksCard
        title={window.t(lang, "common.relatedTools", "Related tools")}
        lang={lang}
        navigate={navigate}
        links={[
          { label: window.t(lang, "nav.faq", "FAQ"), route: "faq" },
          { label: window.t(lang, "footer.privacy", "Privacy policy"), route: "privacy" },
          { label: window.t(lang, "footer.terms", "Terms"), route: "terms" },
          { label: window.t(lang, "calc.typeMortgage", "Mortgage Calculator"), route: "mortgage" },
        ]}
      />
    </div>
  );
}

/* ═════════════════════════════════════════════════════════════
   LEGAL PAGES — Privacy, Terms, Cookies (RODO + ePrivacy compliant)
   ═════════════════════════════════════════════════════════════ */
function LegalPage({ kind, navigate, lang }) {
  const data = (window.getLegalContent && window.getLegalContent(lang, kind))
    || (window.LEGAL_CONTENT_I18N && window.LEGAL_CONTENT_I18N.en && window.LEGAL_CONTENT_I18N.en[kind])
    || (window.LEGAL_CONTENT_I18N && window.LEGAL_CONTENT_I18N.en && window.LEGAL_CONTENT_I18N.en.privacy);

  return (
    <div className="container">
      <Breadcrumbs items={[{ label: window.t(lang, "common.home", "Home"), route: "home" }, { label: data.title }]} navigate={navigate} />
      <PageHeader title={data.title} sub={`${window.t(lang, "pages.legal.lastUpdate", "Last update")}: ${data.updated}`} />
      <div style={{ maxWidth: 800 }}>
        {data.intro && (
          <p style={{ fontSize: 15, color: "var(--text-2)", lineHeight: 1.7, marginBottom: 24, padding: 16, background: "var(--bg-2)", borderRadius: 10, borderLeft: "3px solid var(--accent)" }}>
            {data.intro}
          </p>
        )}
        {data.sections.map(([title, body], i) => (
          <div key={i} style={{ marginBottom: 28 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: "-0.01em" }}>{i + 1}. {title}</h2>
            <div style={{ marginTop: 8, fontSize: 14, color: "var(--text-2)", lineHeight: 1.7 }}>
              {Array.isArray(body) ? (
                body.map((p, j) =>
                  Array.isArray(p) ? (
                    <ul key={j} style={{ marginTop: 8, paddingLeft: 24 }}>
                      {p.map((li, k) => <li key={k} style={{ marginBottom: 4 }}>{li}</li>)}
                    </ul>
                  ) : (
                    <p key={j} style={{ marginTop: j > 0 ? 12 : 0 }}>{p}</p>
                  )
                )
              ) : (
                <p style={{ margin: 0 }}>{body}</p>
              )}
            </div>
          </div>
        ))}
        {kind === "cookies" && (
          <div style={{ marginTop: 32, padding: 20, background: "var(--accent-soft)", borderRadius: 12, border: "1px solid var(--accent)" }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>🍪 {window.t(lang, "common.changeCookiePrefs", "Change your cookie preferences")}</h3>
            <p style={{ marginTop: 8, fontSize: 13, color: "var(--text-2)" }}>
              {window.t(lang, "common.changeCookiePrefsDesc", "You can update your cookie settings at any time.")}
            </p>
            <button
              className="btn btn-primary"
              onClick={() => window.openCookieSettings && window.openCookieSettings()}
              style={{ marginTop: 12 }}
            >
              ⚙ {window.t(lang, "common.cookieSettings", "Cookie Settings")}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* Minimal local fallback; primary legal content comes from src/legal-i18n.jsx */
const LEGAL_CONTENT = {
  privacy: { title: "Privacy Policy", updated: "2026-05-20", intro: "", sections: [] },
  terms: { title: "Terms of Service", updated: "2026-05-20", intro: "", sections: [] },
  cookies: { title: "Cookie Policy", updated: "2026-05-20", intro: "", sections: [] },
};

Object.assign(window, {
  HomePage, CalcPage, BanksPage, MarketsPage, ProgramsPage, ArticlesPage, ArticlePage, FaqPage, ContactPage, LegalPage,
});
