// ─────────────────────────────────────────────────────────────────────────
// calculator.jsx — Main credit calculator + tile system for home page
// ─────────────────────────────────────────────────────────────────────────

const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC } = React;

/* ────────── Mini calculator (compact, for home bento) ────────── */
function MiniCalculator({ country, navigate, lang = "pl" }) {
  const c = window.COUNTRIES.find(x => x.code === country) || window.COUNTRIES[0];
  const T = (k, fb) => window.t(lang, `calc.${k}`, fb);
  const [amount, setAmount] = useStateC(400000);
  const [years, setYears] = useStateC(25);
  const [type, setType] = useStateC("mortgage");

  const months = years * 12;
  const rate = type === "mortgage" ? c.avg : (c.avg + 6.5);
  const monthly = window.annuity(amount, rate, months);
  const total = monthly * months;
  const interest = total - amount;

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, height: "100%" }} className="kr-calc-grid">
      {/* Inputs */}
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        <div style={{ display: "flex", gap: 4, background: "var(--bg-2)", padding: 4, borderRadius: 12, border: "1px solid var(--border-soft)" }}>
          {[
            { k: "mortgage", l: T("typeMortgage", "🏠 Hipoteczny") },
            { k: "cash", l: T("typeCash", "💳 Cash Loan") },
          ].map(t => (
            <button key={t.k} onClick={() => setType(t.k)}
              style={{
                flex: 1, padding: "8px 12px",
                background: type === t.k ? "var(--surface)" : "transparent",
                color: type === t.k ? "var(--text)" : "var(--text-2)",
                border: "none", borderRadius: 8,
                fontSize: 12, fontWeight: 700, cursor: "pointer",
                boxShadow: type === t.k ? "var(--shadow-sm)" : "none",
                transition: "all 0.14s",
              }}>
              {t.l}
            </button>
          ))}
        </div>

        <Field label={T("amount", "Loan Amount")} suffix={c.currency}>
          <input className="input" type="number" value={amount}
            onChange={e => setAmount(Math.max(1000, +e.target.value || 0))}
            style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 18 }} />
          <input type="range" min={type === "mortgage" ? 50000 : 1000} max={type === "mortgage" ? 2000000 : 150000} step={type === "mortgage" ? 10000 : 1000}
            value={amount} onChange={e => setAmount(+e.target.value)} style={rangeStyle()} />
        </Field>

        <Field label={T("period", "Repayment Period")} suffix={T("years", "years")}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span className="num-mono" style={{ fontSize: 28, fontWeight: 700, color: "var(--text)", minWidth: 60 }}>{years}</span>
            <input type="range" min={1} max={type === "mortgage" ? 40 : 10} value={years}
              onChange={e => setYears(+e.target.value)} style={{ ...rangeStyle(), flex: 1 }} />
          </div>
        </Field>
      </div>

      {/* Result */}
      <div style={{
        background: "linear-gradient(155deg, var(--surface-2), var(--surface))",
        border: "1px solid var(--border-soft)",
        borderRadius: 16,
        padding: 24,
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        position: "relative", overflow: "hidden",
      }}>
        <div style={{ position: "absolute", top: -40, right: -40, width: 160, height: 160, borderRadius: "50%", background: "var(--accent-soft)", filter: "blur(40px)" }} />

        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>
            {T("monthlyPayment", "Monthly Payment")} · {rate.toFixed(2)}%
          </div>
          <div style={{ fontSize: "clamp(28px, 4vw, 40px)", fontWeight: 800, letterSpacing: "-0.02em", color: "var(--text)" }}>
            <AnimatedNumber value={monthly} digits={0} /> <span style={{ fontSize: 16, color: "var(--text-3)" }}>{c.currency}</span>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 16 }}>
          <Stat label={T("totalInterest", "Total Interest")} value={interest} currency={c.currency} />
          <Stat label={T("toRepay", "Total Payable")} value={total} currency={c.currency} />
        </div>

        <button className="btn btn-primary" onClick={() => navigate(type === "mortgage" ? "mortgage" : "cash")} style={{ marginTop: 18, width: "100%", justifyContent: "center" }}>
          {T("openFull", "Open Full Calculator")} <ArrowRight />
        </button>
      </div>
    </div>
  );
}

function Field({ label, suffix, children }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
        <label style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{label}</label>
        {suffix && <span style={{ fontSize: 11, fontWeight: 600, color: "var(--text-3)" }}>{suffix}</span>}
      </div>
      {children}
    </div>
  );
}

function Stat({ label, value, currency }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 }}>{label}</div>
      <div className="num-mono" style={{ fontSize: 14, fontWeight: 700, color: "var(--text)" }}>
        {window.formatMoney(value, currency)}
      </div>
    </div>
  );
}

function rangeStyle() {
  return {
    width: "100%",
    height: 4,
    background: "var(--surface-2)",
    borderRadius: 999,
    outline: "none",
    appearance: "none",
    cursor: "pointer",
    marginTop: 8,
    accentColor: "var(--accent)",
  };
}

/* ────────── Full calculator (mortgage/cash) ────────── */
function FullCalculator({ country, mode = "mortgage", navigate, lang = "pl" }) {
  const c = window.COUNTRIES.find(x => x.code === country) || window.COUNTRIES[0];
  const T = (k, fb) => window.t(lang, `calc.${k}`, fb);
  const banksForCountry = window.BANKS.filter(b => b.country === country);
  const allBanks = banksForCountry.length > 0 ? banksForCountry : window.BANKS.filter(b => b.country === "pl");
  const [selectedBank, setSelectedBank] = useStateC(allBanks[0]);
  const [amount, setAmount] = useStateC(mode === "mortgage" ? 400000 : 30000);
  const [years, setYears] = useStateC(mode === "mortgage" ? 25 : 5);
  const [income, setIncome] = useStateC(8000);
  const [obligations, setObligations] = useStateC(800);
  const [rateMode, setRateMode] = useStateC("equal");
  const [downpay, setDownpay] = useStateC(20);

  // ───── Real bank questions (detailed scoring) ─────
  const [step, setStep] = useStateC(1);
  const [showDetailed, setShowDetailed] = useStateC(false);
  const [profile, setProfile] = useStateC({
    employment: "uop_perm",      // UoP bezterm., terminowa, B2B, zlecenie/dzieło, emerytura, rolnik
    tenure: "3y+",                // staż: 3y+, 1-3y, 6-12m, 0-6m, próbny
    bizYears: "na",               // dla B2B: 2+, 1-2, <1
    civilStatus: "married",       // singiel, małżeństwo, partnerstwo, rozwiedziony
    household: 2,                 // liczba osób
    children: 0,                  // dzieci na utrzymaniu
    benefit800: 0,                // 800+ świadczenie
    age: "30-40",                 // do30, 30-40, 40-50, 50-60, 60+
    bik: "clean",                 // clean, minor, major, none
    coIncome: 0,                  // dochód współwnioskodawcy
    extraIncome: 0,               // inne dochody
    cardLimits: 0,                // limity kart
    alimony: 0,                   // alimenty wypłacane
    propertyType: "apt_secondary",// rodzaj nieruchomości
    propertyLocation: "big_city", // lokalizacja
    propertyState: "good",        // stan
    propertyPurpose: "own",       // przeznaczenie
  });

  useEffectC(() => {
    if (!allBanks.find(b => b.id === selectedBank.id)) setSelectedBank(allBanks[0]);
  }, [country]);

  const months = years * 12;
  const rate = mode === "mortgage" ? selectedBank.mortgage : selectedBank.cash;
  const monthly = window.annuity(amount, rate, months);
  const total = monthly * months;
  const interest = total - amount;
  const provision = amount * (selectedBank.prov / 100);
  const totalCost = interest + provision;

  // ───── Detailed scoring (realne pytania bankowe) ─────
  const totalIncome = income + (profile.coIncome || 0) + (profile.extraIncome || 0) + (profile.benefit800 || 0);
  const totalObligations = obligations + ((profile.cardLimits || 0) * 0.05) + (profile.alimony || 0);
  const dti = totalIncome > 0 ? ((monthly + totalObligations) / totalIncome) * 100 : 100;

  const scoringFactors = useMemoC(() => {
    const f = [];
    // Forma zatrudnienia
    const empWeights = { uop_perm: 20, uop_temp: 10, b2b: 15, contract: 5, pension: 18, farmer: 8 };
    f.push({ label: window.t(lang, "calc.scoreEmployment", "Employment Type"), value: empWeights[profile.employment] || 5, max: 20 });
    // Staż
    const tenW = { "3y+": 15, "1-3y": 10, "6-12m": 5, "0-6m": 1, probation: 0 };
    f.push({ label: window.t(lang, "calc.scoreTenure", "Employment Tenure"), value: tenW[profile.tenure] || 5, max: 15 });
    // BIK
    const bikW = { clean: 25, minor: 12, major: 0, none: 8 };
    f.push({ label: window.t(lang, "calc.scoreHistory", "Credit History"), value: bikW[profile.bik] || 8, max: 25 });
    // DTI
    const dtiScore = dti <= 30 ? 20 : dti <= 50 ? 14 : dti <= 65 ? 6 : 0;
    f.push({ label: window.t(lang, "calc.scoreDti", "DTI Ratio"), value: dtiScore, max: 20 });
    // Wiek
    const ageW = { "do30": 8, "30-40": 10, "40-50": 9, "50-60": 6, "60+": 3 };
    f.push({ label: window.t(lang, "calc.scoreAge", "Applicant Age"), value: ageW[profile.age] || 8, max: 10 });
    // Wkład własny (tylko hipoteka)
    if (mode === "mortgage") {
      const dpScore = downpay >= 40 ? 10 : downpay >= 20 ? 7 : downpay >= 10 ? 3 : 0;
      f.push({ label: window.t(lang, "calc.scoreDownPayment", "Down Payment"), value: dpScore, max: 10 });
    }
    return f;
  }, [profile, dti, downpay, mode]);

  const score = Math.min(100, Math.round(
    scoringFactors.reduce((sum, x) => sum + x.value, 0) /
    scoringFactors.reduce((sum, x) => sum + x.max, 0) * 100
  ));

  // Build top-5 ranking for sidebar
  const ranked = [...allBanks].sort((a, b) => (mode === "mortgage" ? a.mortgage - b.mortgage : a.cash - b.cash)).slice(0, 5);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(280px, 1fr)", gap: 24 }} className="kr-fullcalc-grid">
      {/* Form */}
      <div className="card" style={{ padding: 28 }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 24, alignItems: "center", flexWrap: "wrap", gap: 12 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
              {mode === "mortgage" ? T("typeMortgage", "Mortgage") : T("typeCash", "Cash Loan")}
            </div>
            <h2 style={{ margin: "4px 0 0", fontSize: 24, fontWeight: 800, letterSpacing: "-0.02em" }}>
              {T("params", "Loan Parameters")}
            </h2>
          </div>
          <span className="chip">
            {c.flag} {c.name} · {c.rateName} {c.rate}%
          </span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }} className="kr-form-grid">
          <Field label={T("amount", "Loan Amount")} suffix={c.currency}>
            <input className="input" type="number" value={amount} onChange={e => setAmount(Math.max(1000, +e.target.value || 0))}
              style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 18 }} />
            <input type="range" min={mode === "mortgage" ? 50000 : 1000} max={mode === "mortgage" ? 2000000 : 150000} step={mode === "mortgage" ? 10000 : 500}
              value={amount} onChange={e => setAmount(+e.target.value)} style={rangeStyle()} />
          </Field>

          <Field label={T("period", "Repayment Period")} suffix={mode === "mortgage" ? T("years", "years") : T("months", "months")}>
            <input className="input" type="number" value={mode === "mortgage" ? years : years * 12}
              onChange={e => setYears(mode === "mortgage" ? Math.max(1, +e.target.value || 1) : Math.max(1, +e.target.value || 1) / 12)}
              style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 18 }} />
            <input type="range" min={1} max={mode === "mortgage" ? 40 : 10} step={mode === "mortgage" ? 1 : 0.5}
              value={years} onChange={e => setYears(+e.target.value)} style={rangeStyle()} />
          </Field>

          <Field label={window.t(lang, "common.netIncome", "Monthly Net Income")} suffix={c.currency}>
            <input className="input" type="number" value={income} onChange={e => setIncome(Math.max(0, +e.target.value || 0))}
              style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 18 }} />
          </Field>

          <Field label={window.t(lang, "common.monthlyObligations", "Monthly Obligations")} suffix={c.currency}>
            <input className="input" type="number" value={obligations} onChange={e => setObligations(Math.max(0, +e.target.value || 0))}
              style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 18 }} />
          </Field>

          {mode === "mortgage" && (
            <>
              <Field label={window.t(lang, "common.downPayment", "Down Payment")} suffix="%">
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <span className="num-mono" style={{ fontSize: 24, fontWeight: 700, minWidth: 70 }}>{downpay}%</span>
                  <input type="range" min={0} max={90} value={downpay} onChange={e => setDownpay(+e.target.value)} style={{ ...rangeStyle(), flex: 1 }} />
                </div>
              </Field>
              <Field label={window.t(lang, "common.installmentType", "Installment Type")}>
                <div style={{ display: "flex", gap: 4, background: "var(--bg-2)", padding: 4, borderRadius: 10, border: "1px solid var(--border-soft)" }}>
                  {[["equal", window.t(lang, "common.equalInstallments", "Equal")], ["decreasing", window.t(lang, "common.decreasingInstallments", "Decreasing")]].map(([k, l]) => (
                    <button key={k} onClick={() => setRateMode(k)} style={{
                      flex: 1, padding: "10px 12px",
                      background: rateMode === k ? "var(--surface)" : "transparent",
                      color: rateMode === k ? "var(--text)" : "var(--text-2)",
                      border: "none", borderRadius: 8, fontSize: 13, fontWeight: 700, cursor: "pointer",
                      boxShadow: rateMode === k ? "var(--shadow-sm)" : "none",
                    }}>{l}</button>
                  ))}
                </div>
              </Field>
            </>
          )}
        </div>

        {/* Result hero */}
        <div style={{
          marginTop: 24,
          padding: 24,
          background: "linear-gradient(155deg, var(--accent-soft), transparent 70%), var(--bg-2)",
          borderRadius: 16,
          border: "1px solid var(--border-soft)",
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 20 }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 6 }}>
                {T("monthlyPayment", "Monthly Payment")} · {selectedBank.name}
              </div>
              <div style={{ fontSize: "clamp(40px, 6vw, 64px)", fontWeight: 800, letterSpacing: "-0.03em", lineHeight: 1 }}>
                <AnimatedNumber value={monthly} digits={0} />
                <span style={{ fontSize: "0.4em", color: "var(--text-3)", marginLeft: 8 }}>{c.currency}</span>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "auto auto auto", gap: 24, fontSize: 13 }}>
              <ResultStat label={T("rate", "Rate")} value={rate.toFixed(2) + "%"} />
              <ResultStat label={T("provision", "Fee")} value={window.formatMoney(provision, c.currency)} />
              <ResultStat label={T("totalCost", "Total Cost")} value={window.formatMoney(totalCost, c.currency)} />
            </div>
          </div>
        </div>

        {/* Detailed bank questionnaire — real questions banks ask */}
        <div style={{ marginTop: 24, background: "var(--bg-2)", borderRadius: 16, border: "1px solid var(--border-soft)", overflow: "hidden" }}>
          <button onClick={() => setShowDetailed(!showDetailed)} style={{
            width: "100%", display: "flex", justifyContent: "space-between", alignItems: "center",
            padding: 20, background: "transparent", border: "none", cursor: "pointer",
            color: "var(--text)", textAlign: "left",
          }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 4 }}>
                {T("detailed", "Detailed Credit Assessment")}
              </div>
              <div style={{ fontSize: 16, fontWeight: 800 }}>
                {T("detailedTitle", "Answer the questions banks ask")}
              </div>
              <div style={{ fontSize: 12, color: "var(--text-2)", marginTop: 2 }}>
                {showDetailed ? T("detailedSubOpen", "Banks evaluate 8+ factors") : T("detailedSubClosed", "12 questions, about 2 minutes")}
              </div>
            </div>
            <span style={{ color: "var(--accent)", fontSize: 24, transform: showDetailed ? "rotate(45deg)" : "none", transition: "transform 0.2s" }}>+</span>
          </button>

          {showDetailed && (
            <div style={{ padding: "0 20px 20px", borderTop: "1px solid var(--border-soft)" }}>
              <DetailedProfile profile={profile} setProfile={setProfile} mode={mode} currency={c.currency} lang={lang} />
            </div>
          )}
        </div>

        {/* DTI + score */}
        <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }} className="kr-form-grid">
          <div style={{ padding: 16, background: "var(--bg-2)", borderRadius: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
              <span style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{T("dti", "DTI (payment/income)")}</span>
              <span className="num-mono" style={{ fontWeight: 800, color: dti > 50 ? "var(--bad)" : dti > 35 ? "var(--warn)" : "var(--good)" }}>{dti.toFixed(1)}%</span>
            </div>
            <ProgressBar value={dti} />
            <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 8 }}>
              {T("dtiHint", "Banks prefer DTI below 50%")}
            </div>
          </div>
          <div style={{ padding: 16, background: score > 70 ? "color-mix(in oklch, var(--good) 8%, var(--bg-2))" : "var(--bg-2)", borderRadius: 12, border: "1px solid " + (score > 70 ? "var(--good)" : "var(--border-soft)") }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
              <span style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{T("chances", "Approval Probability")}</span>
              <span className="num-mono" style={{ fontWeight: 800, color: score > 70 ? "var(--good)" : score > 40 ? "var(--warn)" : "var(--bad)" }}>{score}%</span>
            </div>
            <ProgressBar value={score} />
            <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 8 }}>
              {showDetailed ? `${window.t(lang, "common.basedOn", "Based on")} ${scoringFactors.length} ${window.t(lang, "common.factorsWord", "factors")}` : window.t(lang, "common.completeDetailed", "Complete detailed analysis to increase accuracy")}
            </div>
          </div>
        </div>

        {/* Factor breakdown (visible when detailed mode on) */}
        {showDetailed && (
          <div style={{ marginTop: 20, padding: 20, background: "var(--bg-2)", borderRadius: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <h4 style={{ margin: 0, fontSize: 13, fontWeight: 800, letterSpacing: "-0.01em" }}>{T("factors", "Scoring Factors")}</h4>
              <span style={{ fontSize: 11, color: "var(--text-3)" }}>{T("sumPoints", "Total Points")}</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 14 }}>
              {scoringFactors.map((f, i) => {
                const pct = (f.value / f.max) * 100;
                return (
                  <div key={i}>
                    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 12 }}>
                      <span style={{ color: "var(--text-2)", fontWeight: 600 }}>{f.label}</span>
                      <span className="num-mono" style={{ color: pct > 75 ? "var(--good)" : pct > 40 ? "var(--warn)" : "var(--bad)", fontWeight: 700 }}>
                        {f.value}/{f.max}
                      </span>
                    </div>
                    <div style={{ width: "100%", height: 4, background: "var(--surface)", borderRadius: 999, overflow: "hidden" }}>
                      <div style={{ width: pct + "%", height: "100%", background: pct > 75 ? "var(--good)" : pct > 40 ? "var(--warn)" : "var(--bad)", borderRadius: 999, transition: "width 0.6s var(--ease)" }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* Sidebar: bank ranking */}
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="card" style={{ padding: 20 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <h3 style={{ margin: 0, fontSize: 13, fontWeight: 800, letterSpacing: "-0.01em" }}>
              {T("bankRanking", "Bank Ranking")}
            </h3>
            <button onClick={() => navigate("banks")} style={{ background: "none", border: "none", color: "var(--accent)", fontSize: 11, fontWeight: 700, cursor: "pointer" }}>
              {T("allBanks", "All")} →
            </button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {ranked.map((b, i) => (
              <button key={b.id} onClick={() => setSelectedBank(b)} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "10px 12px",
                background: selectedBank.id === b.id ? "var(--surface-2)" : "transparent",
                border: "1px solid " + (selectedBank.id === b.id ? "var(--accent)" : "transparent"),
                borderRadius: 10, cursor: "pointer", width: "100%",
                transition: "all 0.14s",
              }}>
                <span style={{ width: 22, height: 22, borderRadius: 6, background: i === 0 ? "var(--accent)" : "var(--surface-2)", color: i === 0 ? "var(--bg)" : "var(--text-2)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800 }}>{i + 1}</span>
                <span style={{ flex: 1, textAlign: "left", fontSize: 12, fontWeight: 600, color: "var(--text)" }}>{b.name}</span>
                <span className="num-mono" style={{ fontSize: 13, fontWeight: 700, color: i === 0 ? "var(--accent)" : "var(--text)" }}>
                  {(mode === "mortgage" ? b.mortgage : b.cash).toFixed(2)}%
                </span>
              </button>
            ))}
          </div>
        </div>

        <AdSlot size="rect" hint="300×250 in-flow" />

        <div className="card" style={{ padding: 18, background: "linear-gradient(155deg, var(--accent-soft), transparent), var(--surface)" }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>
            {T("aiTip", "AI Tip")}
          </div>
          <p style={{ margin: 0, fontSize: 13, lineHeight: 1.5, color: "var(--text-2)" }}>
            {T("aiTipText1", "Your payment is")} <strong style={{ color: "var(--text)" }}>{((monthly / income) * 100).toFixed(0)}%</strong> {T("aiTipText2", "of your income.")}{" "}
            {dti > 50 ? window.t(lang, "common.reduceAmount", "Reduce amount or extend period.") : dti > 35 ? window.t(lang, "common.safeLevel", "Safe level with some buffer.") : window.t(lang, "common.comfortLevel", "Comfortable level for approval.")}
          </p>
        </div>
      </div>
    </div>
  );
}

/* ────────── Detailed profile (real bank questions) ────────── */
function DetailedProfile({ profile, setProfile, mode, currency, lang = "pl" }) {
  const set = (k, v) => setProfile({ ...profile, [k]: v });
  return (
    <div style={{ display: "grid", gap: 20, marginTop: 16 }}>
      {/* Group: Employment */}
      <ProfileGroup title={window.t(lang, "calc.profileEmploymentTitle", "💼 Employment and Income")} desc={window.t(lang, "calc.profileEmploymentDesc", "Banks first evaluate income stability")}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 14 }}>
          <Field label={window.t(lang, "calc.profileEmploymentType", "Employment Type")}>
            <select className="select" value={profile.employment} onChange={e => set("employment", e.target.value)}>
              <option value="uop_perm">{window.t(lang, "calc.employment.uop_perm", "📋 Permanent Employment Contract")}</option>
              <option value="uop_temp">{window.t(lang, "calc.employment.uop_temp", "📅 Fixed-Term Employment Contract")}</option>
              <option value="b2b">{window.t(lang, "calc.employment.b2b", "🏢 B2B / Self-Employed")}</option>
              <option value="contract">{window.t(lang, "calc.employment.contract", "📝 Civil Contract / Freelance")}</option>
              <option value="pension">{window.t(lang, "calc.employment.pension", "🧓 Pension / Disability Pension")}</option>
              <option value="farmer">{window.t(lang, "calc.employment.farmer", "🌾 Farmer")}</option>
            </select>
          </Field>
          <Field label={window.t(lang, "calc.profileTenure", "Employment Tenure")}>
            <select className="select" value={profile.tenure} onChange={e => set("tenure", e.target.value)}>
              <option value="3y+">{window.t(lang, "calc.tenure.3y+", "Over 3 years ✅")}</option>
              <option value="1-3y">{window.t(lang, "calc.tenure.1-3y", "1–3 years")}</option>
              <option value="6-12m">{window.t(lang, "calc.tenure.6-12m", "6–12 months")}</option>
              <option value="0-6m">{window.t(lang, "calc.tenure.0-6m", "Under 6 months ⚠️")}</option>
              <option value="probation">{window.t(lang, "calc.tenure.probation", "Probation period ⚠️")}</option>
            </select>
          </Field>
          {profile.employment === "b2b" && (
            <Field label={window.t(lang, "calc.profileBizYears", "Years in Business")}>
              <select className="select" value={profile.bizYears} onChange={e => set("bizYears", e.target.value)}>
                <option value="2+">{window.t(lang, "calc.bizYears.2+", "Over 2 years ✅")}</option>
                <option value="1-2">{window.t(lang, "calc.bizYears.1-2", "1–2 years")}</option>
                <option value="<1">{window.t(lang, "calc.bizYears.<1", "Under 1 year ⚠️")}</option>
              </select>
            </Field>
          )}
          <Field label={window.t(lang, "calc.profileCoIncome", "Co-applicant Income")} suffix={currency}>
            <input className="input" type="number" value={profile.coIncome} onChange={e => set("coIncome", +e.target.value || 0)} />
          </Field>
          <Field label={window.t(lang, "calc.profileExtraIncome", "Additional Income (rent, dividends)")} suffix={currency}>
            <input className="input" type="number" value={profile.extraIncome} onChange={e => set("extraIncome", +e.target.value || 0)} />
          </Field>
        </div>
      </ProfileGroup>

      {/* Group: Family situation */}
      <ProfileGroup title={window.t(lang, "calc.profileFamilyTitle", "👨‍👩‍👧 Household Situation")} desc={window.t(lang, "calc.profileFamilyDesc", "Affects household maintenance costs")}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 14 }}>
          <Field label={window.t(lang, "calc.profileCivilStatus", "Marital Status")}>
            <select className="select" value={profile.civilStatus} onChange={e => set("civilStatus", e.target.value)}>
              <option value="single">{window.t(lang, "calc.civil.single", "👤 Single")}</option>
              <option value="married">{window.t(lang, "calc.civil.married", "👫 Married")}</option>
              <option value="partner">{window.t(lang, "calc.civil.partner", "💑 Partnership")}</option>
              <option value="divorced">{window.t(lang, "calc.civil.divorced", "⚖️ Divorced")}</option>
            </select>
          </Field>
          <Field label={window.t(lang, "calc.profileHousehold", "Household Size")}>
            <select className="select" value={profile.household} onChange={e => set("household", +e.target.value)}>
              {[1,2,3,4,5,6].map(n => <option key={n} value={n}>{n} {window.t(lang, "calc.people", "people")}</option>)}
            </select>
          </Field>
          <Field label={window.t(lang, "calc.profileChildren", "Dependent Children")}>
            <select className="select" value={profile.children} onChange={e => set("children", +e.target.value)}>
              {[0,1,2,3,4,5].map(n => <option key={n} value={n}>{n === 0 ? window.t(lang, "calc.children.none", "No children") : `${n} ${window.t(lang, "calc.children.word", "children")}`}</option>)}
            </select>
          </Field>
          <Field label={window.t(lang, "calc.profileBenefit", "Child Benefit (monthly)")} suffix={currency}>
            <input className="input" type="number" value={profile.benefit800} onChange={e => set("benefit800", +e.target.value || 0)} />
          </Field>
          <Field label={window.t(lang, "calc.profileAge", "Applicant Age")}>
            <select className="select" value={profile.age} onChange={e => set("age", e.target.value)}>
              <option value="do30">{window.t(lang, "calc.age.do30", "under 30")}</option>
              <option value="30-40">{window.t(lang, "calc.age.30-40", "30–40 ✅")}</option>
              <option value="40-50">{window.t(lang, "calc.age.40-50", "40–50")}</option>
              <option value="50-60">{window.t(lang, "calc.age.50-60", "50–60")}</option>
              <option value="60+">{window.t(lang, "calc.age.60+", "over 60 ⚠️")}</option>
            </select>
          </Field>
        </div>
      </ProfileGroup>

      {/* Group: Liabilities & BIK */}
      <ProfileGroup title={window.t(lang, "calc.profileLiabilitiesTitle", "💳 Liabilities and Credit History")} desc={window.t(lang, "calc.profileLiabilitiesDesc", "Banks verify credit history before each decision")}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 14 }}>
          <Field label={window.t(lang, "calc.profileCardLimits", "Card and Overdraft Limits")} suffix={currency}>
            <input className="input" type="number" value={profile.cardLimits} onChange={e => set("cardLimits", +e.target.value || 0)} />
          </Field>
          <Field label={window.t(lang, "calc.profileAlimony", "Alimony Payments (monthly)")} suffix={currency}>
            <input className="input" type="number" value={profile.alimony} onChange={e => set("alimony", +e.target.value || 0)} />
          </Field>
          <Field label={window.t(lang, "calc.profileBik", "Credit History (BIK)")}>
            <select className="select" value={profile.bik} onChange={e => set("bik", e.target.value)}>
              <option value="clean">{window.t(lang, "calc.bik.clean", "✅ No Delays")}</option>
              <option value="minor">{window.t(lang, "calc.bik.minor", "⚠️ Minor Delays")}</option>
              <option value="major">{window.t(lang, "calc.bik.major", "❌ Serious Issues")}</option>
              <option value="none">{window.t(lang, "calc.bik.none", "❓ No Credit History")}</option>
            </select>
          </Field>
        </div>
      </ProfileGroup>

      {/* Group: Property (only mortgage) */}
      {mode === "mortgage" && (
        <ProfileGroup title={window.t(lang, "calc.profilePropertyTitle", "🏠 Property")} desc={window.t(lang, "calc.profilePropertyDesc", "Type, location and condition affect max LTV")}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 14 }}>
            <Field label={window.t(lang, "calc.profilePropertyType", "Property Type")}>
              <select className="select" value={profile.propertyType} onChange={e => set("propertyType", e.target.value)}>
                <option value="apt_primary">{window.t(lang, "calc.propertyType.apt_primary", "🏢 Apartment — Primary Market")}</option>
                <option value="apt_secondary">{window.t(lang, "calc.propertyType.apt_secondary", "🏠 Apartment — Secondary Market")}</option>
                <option value="house_primary">{window.t(lang, "calc.propertyType.house_primary", "🏡 House — Primary Market")}</option>
                <option value="house_secondary">{window.t(lang, "calc.propertyType.house_secondary", "🏘️ House — Secondary Market")}</option>
                <option value="plot">{window.t(lang, "calc.propertyType.plot", "🌿 Building Plot")}</option>
                <option value="commercial">{window.t(lang, "calc.propertyType.commercial", "🏪 Commercial Property")}</option>
              </select>
            </Field>
            <Field label={window.t(lang, "calc.profilePropertyLocation", "Location")}>
              <select className="select" value={profile.propertyLocation} onChange={e => set("propertyLocation", e.target.value)}>
                <option value="big_city">{window.t(lang, "calc.propertyLocation.big_city", "🏙️ Large City (100k+)")}</option>
                <option value="mid_city">{window.t(lang, "calc.propertyLocation.mid_city", "🏘️ Mid-size City (20k–100k)")}</option>
                <option value="small_city">{window.t(lang, "calc.propertyLocation.small_city", "🏠 Small City (under 20k)")}</option>
                <option value="village">{window.t(lang, "calc.propertyLocation.village", "🌾 Village / Rural Area")}</option>
              </select>
            </Field>
            <Field label={window.t(lang, "calc.profilePropertyState", "Property Condition")}>
              <select className="select" value={profile.propertyState} onChange={e => set("propertyState", e.target.value)}>
                <option value="developer">{window.t(lang, "calc.propertyState.developer", "🔧 Developer Standard")}</option>
                <option value="to_renovate">{window.t(lang, "calc.propertyState.to_renovate", "🪚 Needs Renovation")}</option>
                <option value="good">{window.t(lang, "calc.propertyState.good", "✅ Good Condition")}</option>
                <option value="renovated">{window.t(lang, "calc.propertyState.renovated", "✨ Renovated / New")}</option>
              </select>
            </Field>
            <Field label={window.t(lang, "calc.profilePropertyPurpose", "Usage Purpose")}>
              <select className="select" value={profile.propertyPurpose} onChange={e => set("propertyPurpose", e.target.value)}>
                <option value="own">{window.t(lang, "calc.propertyPurpose.own", "🏠 Own Residence")}</option>
                <option value="rent">{window.t(lang, "calc.propertyPurpose.rent", "💼 Rental / Investment")}</option>
                <option value="vacation">{window.t(lang, "calc.propertyPurpose.vacation", "🏖️ Vacation Property")}</option>
              </select>
            </Field>
          </div>
        </ProfileGroup>
      )}
    </div>
  );
}

function ProfileGroup({ title, desc, children }) {
  return (
    <div>
      <div style={{ marginBottom: 12 }}>
        <h4 style={{ margin: 0, fontSize: 13, fontWeight: 800, letterSpacing: "-0.01em" }}>{title}</h4>
        {desc && <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{desc}</div>}
      </div>
      {children}
    </div>
  );
}

function ResultStat({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: 4 }}>{label}</div>
      <div className="num-mono" style={{ fontSize: 16, fontWeight: 800, color: "var(--text)" }}>{value}</div>
    </div>
  );
}

/* ────────── Bento Tile renderer ────────── */
function Tile({ tile, country, navigate, density = "regular", lang = "pl" }) {
  const tt = (k, fb) => window.t(lang, `tiles.${tile.kind}.${k}`, fb);
  // Calc kind is special — uses full mini calculator
  if (tile.kind === "calc") {
    return (
      <BentoCard tile={tile} span={tile.size}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 6 }}>
              {tt("kicker", "💰 Kalkulator")}
            </div>
            <h3 style={{ margin: 0, fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{tt("title", tile.title)}</h3>
            {tt("sub", tile.sub) && <p style={{ margin: "4px 0 0", fontSize: 13, color: "var(--text-2)" }}>{tt("sub", tile.sub)}</p>}
          </div>
        </div>
        <MiniCalculator country={country} navigate={navigate} lang={lang} />
      </BentoCard>
    );
  }

  if (tile.kind === "rate") {
    const r = window.REFERENCE_RATES.find(x => x.code === tile.code) || window.REFERENCE_RATES[0];
    return (
      <BentoCard tile={tile} span={tile.size} onClick={() => navigate("markets")}>
        <div style={{ display: "flex", flexDirection: "column", height: "100%", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
              <span className="live-dot" style={{ marginRight: 6 }} /> {window.t(lang, "common.live", "Live")}
            </div>
            <div style={{ marginTop: 12, fontSize: 13, fontWeight: 700, color: "var(--text-2)" }}>{r.name}</div>
            <div className="num-mono" style={{ fontSize: 36, fontWeight: 800, letterSpacing: "-0.03em", marginTop: 4 }}>
              {r.value.toFixed(2)}<span style={{ fontSize: 18, color: "var(--text-3)" }}>%</span>
            </div>
            <TrendPill value={r.change} />
          </div>
          <Sparkline data={r.trend} width={120} height={36} />
        </div>
      </BentoCard>
    );
  }

  if (tile.kind === "fx") {
    return (
      <BentoCard tile={tile} span={tile.size} onClick={() => navigate("markets")}>
        <TileHeader tile={tile} icon="💱" tt={tt} />
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 14 }}>
          {window.FX.slice(0, 4).map(fx => (
            <div key={fx.pair} style={{ display: "grid", gridTemplateColumns: "60px 1fr auto", gap: 8, alignItems: "center", fontSize: 13 }}>
              <span style={{ color: "var(--text-3)", fontWeight: 700, fontSize: 11 }}>{fx.pair}</span>
              <span className="num-mono" style={{ fontWeight: 700, color: "var(--text)" }}>{fx.value.toFixed(4)}</span>
              <TrendPill value={fx.d24} />
            </div>
          ))}
        </div>
      </BentoCard>
    );
  }

  if (tile.kind === "banks") {
    const top = [...window.BANKS].filter(b => b.country === country || country === "pl").sort((a, b) => a.mortgage - b.mortgage).slice(0, 5);
    return (
      <BentoCard tile={tile} span={tile.size} onClick={() => navigate("banks")}>
        <TileHeader tile={tile} icon="🏦" tt={tt} />
        <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 14 }}>
          {top.map((b, i) => (
            <div key={b.id} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12 }}>
              <span style={{ width: 16, color: "var(--text-3)", fontWeight: 700, textAlign: "center" }}>{i + 1}</span>
              <span style={{ flex: 1, color: "var(--text)", fontWeight: 600 }}>{b.name}</span>
              <span className="num-mono" style={{ fontWeight: 700, color: i === 0 ? "var(--accent)" : "var(--text)" }}>{b.mortgage.toFixed(2)}%</span>
            </div>
          ))}
        </div>
      </BentoCard>
    );
  }

  if (tile.kind === "programs") {
    const localizedPrograms = (window.getLocalizedPrograms && window.getLocalizedPrograms(lang)) || window.PROGRAMS;
    return (
      <BentoCard tile={tile} span={tile.size} onClick={() => navigate("programs")}>
        <TileHeader tile={tile} icon="🏛️" tt={tt} />
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
          {localizedPrograms.slice(0, 4).map(p => {
            const c = window.COUNTRIES.find(c => c.code === p.country);
            return (
              <div key={p.id} style={{
                padding: "8px 12px",
                background: "var(--bg-2)",
                border: "1px solid var(--border-soft)",
                borderRadius: 10,
                fontSize: 12, fontWeight: 600,
                display: "flex", alignItems: "center", gap: 6,
              }}>
                <span>{c?.flag}</span>
                <span>{p.name.split("—")[0].split(" ").slice(0, 3).join(" ")}</span>
              </div>
            );
          })}
        </div>
        <div style={{ marginTop: 12, fontSize: 12, color: "var(--text-2)" }}>
          {tt("footer", "7+ subsidy programs in Europe")}
        </div>
      </BentoCard>
    );
  }

  if (tile.kind === "ai") {
    return (
      <BentoCard tile={tile} span={tile.size} accent>
        <TileHeader tile={tile} icon="🤖" tt={tt} />
        <p style={{ margin: "14px 0 12px", fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>
          {tt("body", "Enter amount and income — AI estimates your loan approval chances using 12 factors.")}
        </p>
        <button className="btn btn-primary" onClick={() => navigate("mortgage")} style={{ fontSize: 12 }}>
          {tt("cta", "Check Chances")} <ArrowRight />
        </button>
      </BentoCard>
    );
  }

  if (tile.kind === "compare") {
    return (
      <BentoCard tile={tile} span={tile.size} onClick={() => navigate("mortgage")}>
        <TileHeader tile={tile} icon="⚖️" tt={tt} />
        <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <div style={{ padding: 12, background: "var(--bg-2)", borderRadius: 10 }}>
            <div style={{ fontSize: 11, color: "var(--text-3)", fontWeight: 700, marginBottom: 4 }}>🇵🇱 PLN</div>
            <div className="num-mono" style={{ fontSize: 18, fontWeight: 800 }}>6.80%</div>
            <div style={{ fontSize: 10, color: "var(--text-3)" }}>{tt("pln", "avg rate")}</div>
          </div>
          <div style={{ padding: 12, background: "var(--accent-soft)", borderRadius: 10 }}>
            <div style={{ fontSize: 11, color: "var(--accent)", fontWeight: 700, marginBottom: 4 }}>🇪🇺 EUR</div>
            <div className="num-mono" style={{ fontSize: 18, fontWeight: 800, color: "var(--accent)" }}>3.85%</div>
            <div style={{ fontSize: 10, color: "var(--text-3)" }}>{tt("eur", "avg rate")}</div>
          </div>
        </div>
        <div style={{ marginTop: 10, fontSize: 11, color: "var(--text-3)" }}>
          {tt("diffNote", "≈ 2,100 PLN monthly difference on a 400k loan")}
        </div>
      </BentoCard>
    );
  }

  if (tile.kind === "changes") {
    const changes = [...window.BANKS].sort((a, b) => Math.abs(b.trend) - Math.abs(a.trend)).slice(0, 4);
    return (
      <BentoCard tile={tile} span={tile.size} onClick={() => navigate("banks")}>
        <TileHeader tile={tile} icon="📡" tt={tt} />
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 14 }}>
          {changes.map(b => {
            const c = window.COUNTRIES.find(c => c.code === b.country);
            const up = b.trend > 0;
            const flat = Math.abs(b.trend) < 0.005;
            return (
              <div key={b.id} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 8, alignItems: "center", fontSize: 12 }}>
                <span style={{ fontSize: 14 }}>{c?.flag}</span>
                <span style={{ color: "var(--text)", fontWeight: 600 }}>{b.name}</span>
                <span className="num-mono" style={{ color: "var(--text-3)", fontSize: 11 }}>{b.mortgage.toFixed(2)}%</span>
                <span style={{
                  color: flat ? "var(--text-3)" : (up ? "var(--bad)" : "var(--good)"),
                  fontSize: 11, fontWeight: 700, fontFamily: "var(--font-mono)",
                  display: "inline-flex", alignItems: "center", gap: 2,
                }}>
                  {flat ? "→" : (up ? "▲" : "▼")}{Math.abs(b.trend).toFixed(2)}
                </span>
              </div>
            );
          })}
        </div>
        <div style={{ marginTop: 10, fontSize: 11, color: "var(--text-3)" }}>
          <span className="live-dot" style={{ marginRight: 6 }} /> {window.t(lang, "common.weeklyUpdate", "Weekly update")}
        </div>
      </BentoCard>
    );
  }

  if (tile.kind === "ad") {
    return (
      <BentoCard tile={tile} span={tile.size} plain>
        <AdSlot size="in_grid" label="In-grid 300×250" hint="design-friendly" />
      </BentoCard>
    );
  }

  if (tile.kind === "articles") {
    const localizedArticles = (window.getLocalizedArticles && window.getLocalizedArticles(lang)) || window.ARTICLES;
    return (
      <BentoCard tile={tile} span={tile.size}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 18, alignItems: "center" }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{tt("kicker", "📚 Wiedza")}</div>
            <h3 style={{ margin: "4px 0 0", fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{tt("title", tile.title)}</h3>
          </div>
          <button onClick={() => navigate("articles")} style={{ background: "none", border: "none", color: "var(--accent)", fontWeight: 700, fontSize: 12, cursor: "pointer" }}>
            {window.t(lang, "cta.seeAll", "All →")}
          </button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
          {localizedArticles.slice(0, 3).map(a => (
            <button key={a.id} onClick={() => navigate({ name: "article", id: a.id })} style={{
              padding: 0, background: "transparent", border: "none", cursor: "pointer", textAlign: "left",
              display: "flex", flexDirection: "column", gap: 8, transition: "transform 0.2s",
            }} onMouseEnter={e => e.currentTarget.querySelector('.thumb').style.transform = "scale(1.04)"}
               onMouseLeave={e => e.currentTarget.querySelector('.thumb').style.transform = "scale(1)"}>
              <div className="thumb" style={{ width: "100%", aspectRatio: "16/10", background: a.img, borderRadius: 10, transition: "transform 0.4s var(--ease)" }} />
              <span style={{ fontSize: 10, fontWeight: 700, color: "var(--accent)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{a.cat}</span>
              <span style={{ fontSize: 14, fontWeight: 700, color: "var(--text)", lineHeight: 1.3 }}>{a.title}</span>
              <span style={{ fontSize: 11, color: "var(--text-3)" }}>{a.read} {window.t(lang, "common.minutes", "min read")}</span>
            </button>
          ))}
        </div>
      </BentoCard>
    );
  }

  return null;
}

function TileHeader({ tile, icon, tt }) {
  const title = tt ? tt("title", tile.title) : tile.title;
  const sub = tt ? tt("sub", tile.sub) : tile.sub;
  return (
    <div>
      <div style={{ fontSize: 22, marginBottom: 6 }}>{icon}</div>
      <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: "-0.02em" }}>{title}</h3>
      {sub && <p style={{ margin: "4px 0 0", fontSize: 12, color: "var(--text-2)" }}>{sub}</p>}
    </div>
  );
}

function BentoCard({ tile, span = "md", children, accent = false, plain = false, onClick }) {
  const gridSpans = {
    xl:   { col: "span 8", row: "span 2", minH: 380 },
    full: { col: "span 8", row: "span 1", minH: 280 },
    lg:   { col: "span 6", row: "span 1", minH: 260 },
    md:   { col: "span 4", row: "span 1", minH: 220 },
    sm:   { col: "span 2", row: "span 1", minH: 220 },
  };
  const s = gridSpans[span] || gridSpans.md;
  const baseStyle = {
    gridColumn: s.col,
    gridRow: s.row,
    minHeight: s.minH,
    padding: plain ? 0 : 24,
    background: accent ? "linear-gradient(155deg, var(--accent-soft), transparent 70%), var(--surface)" : "var(--surface)",
    border: "1px solid " + (accent ? "var(--accent)" : "var(--border-soft)"),
    borderRadius: "var(--radius-lg)",
    cursor: onClick ? "pointer" : "default",
    transition: "all 0.22s var(--ease)",
    display: "flex", flexDirection: "column",
    overflow: "hidden",
    position: "relative",
  };
  return (
    <div onClick={onClick} style={baseStyle}
      className={`bento-card bento-span-${span} fade-up`}
      onMouseEnter={e => {
        if (onClick) {
          e.currentTarget.style.transform = "translateY(-3px)";
          e.currentTarget.style.boxShadow = "var(--shadow)";
        }
      }}
      onMouseLeave={e => {
        e.currentTarget.style.transform = "translateY(0)";
        e.currentTarget.style.boxShadow = "none";
      }}>
      {children}
    </div>
  );
}

Object.assign(window, {
  MiniCalculator, FullCalculator, Tile, BentoCard, Field, Stat,
});
