import { useState, useEffect, useMemo, useCallback } from "react";
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell, RadarChart, Radar, PolarGrid, PolarAngleAxis } from "recharts";

// ═══════════════════════════════════════════════════════════════════════════
// DONNÉES COMMUNES BELGES
// Source: Statbel baromètre immobilier (open data), Notaire.be publications
// centimes: centimes additionnels au précompte immobilier (/ communes.be)
// rc: revenu cadastral moyen pour appt 2ch (estimation SPF Finances)
// ═══════════════════════════════════════════════════════════════════════════
const COMMUNES = [
  {id:"CHA",name:"Charleroi",   reg:"WAL",prov:"Hainaut",        prix:145000,loyer:720, rc:850, cent:28.0,trend:+0.3,pop:202000},
  {id:"LGE",name:"Liège",       reg:"WAL",prov:"Liège",           prix:165000,loyer:780, rc:920, cent:29.0,trend:+0.2,pop:197000},
  {id:"NAM",name:"Namur",       reg:"WAL",prov:"Namur",           prix:185000,loyer:850, rc:980, cent:26.5,trend: 0.0,pop:113000},
  {id:"MON",name:"Mons",        reg:"WAL",prov:"Hainaut",         prix:160000,loyer:750, rc:900, cent:27.5,trend:+0.1,pop:97000},
  {id:"ARL",name:"Arlon",       reg:"WAL",prov:"Luxembourg",      prix:210000,loyer:800, rc:950, cent:24.0,trend:+0.2,pop:30000},
  {id:"TOU",name:"Tournai",     reg:"WAL",prov:"Hainaut",         prix:155000,loyer:700, rc:880, cent:27.0,trend:+0.1,pop:68000},
  {id:"LOL",name:"La Louvière", reg:"WAL",prov:"Hainaut",         prix:140000,loyer:680, rc:820, cent:28.5,trend: 0.0,pop:80000},
  {id:"VER",name:"Verviers",    reg:"WAL",prov:"Liège",           prix:140000,loyer:670, rc:800, cent:30.0,trend:-0.1,pop:56000},
  {id:"WAV",name:"Wavre",       reg:"WAL",prov:"Brabant W.",      prix:290000,loyer:1000,rc:1150,cent:18.0,trend:+0.1,pop:34000},
  {id:"WTL",name:"Waterloo",    reg:"WAL",prov:"Brabant W.",      prix:420000,loyer:1300,rc:1700,cent:16.0,trend: 0.0,pop:30000},
  {id:"OTB",name:"Ottignies-LLN",reg:"WAL",prov:"Brabant W.",    prix:310000,loyer:1050,rc:1200,cent:17.0,trend:+0.1,pop:29000},
  {id:"BXL",name:"Bruxelles",   reg:"BXL",prov:"Bruxelles",       prix:380000,loyer:1200,rc:1500,cent:12.5,trend: 0.0,pop:184000},
  {id:"SCH",name:"Schaerbeek",  reg:"BXL",prov:"Bruxelles",       prix:320000,loyer:1050,rc:1300,cent:13.5,trend:+0.1,pop:133000},
  {id:"AND",name:"Anderlecht",  reg:"BXL",prov:"Bruxelles",       prix:295000,loyer:980, rc:1200,cent:14.0,trend:+0.1,pop:120000},
  {id:"IXL",name:"Ixelles",     reg:"BXL",prov:"Bruxelles",       prix:450000,loyer:1400,rc:1800,cent:11.0,trend:+0.1,pop:88000},
  {id:"UCL",name:"Uccle",       reg:"BXL",prov:"Bruxelles",       prix:580000,loyer:1600,rc:2200,cent: 9.0,trend: 0.0,pop:82000},
  {id:"ANT",name:"Anvers",      reg:"FL", prov:"Anvers",          prix:280000,loyer:1050,rc:1100,cent:26.5,trend: 0.0,pop:530000},
  {id:"GHT",name:"Gand",        reg:"FL", prov:"Flandre-Or.",     prix:310000,loyer:1100,rc:1200,cent:25.0,trend:+0.1,pop:263000},
  {id:"BRG",name:"Bruges",      reg:"FL", prov:"Flandre-Occ.",    prix:295000,loyer:950, rc:1100,cent:23.5,trend:+0.1,pop:118000},
  {id:"LVN",name:"Louvain",     reg:"FL", prov:"Brabant fl.",     prix:290000,loyer:950, rc:1100,cent:24.0,trend: 0.0,pop:102000},
  {id:"HST",name:"Hasselt",     reg:"FL", prov:"Limbourg",        prix:220000,loyer:900, rc:1000,cent:23.0,trend:+0.4,pop:79000},
  {id:"CRT",name:"Courtrai",    reg:"FL", prov:"Flandre-Occ.",    prix:235000,loyer:880, rc:1050,cent:24.5,trend:+0.1,pop:76000},
  {id:"GNK",name:"Genk",        reg:"FL", prov:"Limbourg",        prix:200000,loyer:820, rc:950, cent:25.0,trend:+0.3,pop:66000},
  {id:"ALT",name:"Alost",       reg:"FL", prov:"Flandre-Or.",     prix:245000,loyer:870, rc:1050,cent:25.5,trend:+0.1,pop:83000},
  {id:"MCH",name:"Malines",     reg:"FL", prov:"Anvers",          prix:255000,loyer:900, rc:1080,cent:25.0,trend:+0.2,pop:86000},
  {id:"OST",name:"Ostende",     reg:"FL", prov:"Flandre-Occ.",    prix:280000,loyer:920, rc:1080,cent:24.0,trend:+0.2,pop:70000},
  {id:"TRH",name:"Turnhout",    reg:"FL", prov:"Anvers",          prix:215000,loyer:820, rc:980, cent:26.0,trend:+0.1,pop:44000},
  {id:"ROX",name:"Roeselaere",  reg:"FL", prov:"Flandre-Occ.",    prix:220000,loyer:800, rc:1000,cent:25.5,trend:+0.1,pop:60000},
];

// ═══════════════════════════════════════════════════════════════════════════
// MOTEUR DE CALCUL FINANCIER BELGE
// Formules basées sur la législation fiscale BE 2024
// ═══════════════════════════════════════════════════════════════════════════
function calcFinancials(f) {
  const prix = +f.prixAchat || 0;
  const loyer = +f.loyer || 0;
  const rc = +f.rc || 900;
  const surface = +f.surface || 70;
  const cent = +f.centimes || 25;
  const fnot = +f.fraisNotaire || 12.5;
  const travaux = +f.travaux || 0;
  const credit = +f.credit || 0;

  const invest = prix * (1 + fnot / 100) + travaux;
  const brutAn = loyer * 12;
  const rentBrut = invest > 0 ? brutAn / invest * 100 : 0;

  // Précompte immobilier = RC × (centimes/100)
  const precompte = rc * (cent / 100);

  // Charges annuelles réelles estimées
  const syndic = surface * 1.2 * 12;
  const assurance = invest * 0.002;
  const entretien = invest * 0.004;
  const chargesTotal = syndic + assurance + entretien + precompte;

  // ── IPP (Impôt des Personnes Physiques) ──────────────────────────────
  // Base imposable = RC × 1.4 (indexé) − 40% forfait charges
  const rcImpute = rc * 1.4;
  const baseIPP = rcImpute * 0.60;
  // Taux marginal 45% (revenus moyens salariés BE)
  const impotIPP = baseIPP * 0.45;
  const netIPP = brutAn - chargesTotal - impotIPP;
  const rentNetIPP = invest > 0 ? netIPP / invest * 100 : 0;

  // ── ISoc (Impôt des Sociétés) ─────────────────────────────────────────
  // Base = loyer réel − charges réelles (30%) − amortissements (3%/an)
  const amort = prix * 0.03;
  const chargesIsoc = brutAn * 0.30 + amort;
  const baseIsoc = Math.max(brutAn - chargesIsoc, 0);
  const impotIsoc = baseIsoc * 0.25;
  const netIsoc = brutAn - brutAn * 0.30 - impotIsoc;
  const rentNetIsoc = invest > 0 ? netIsoc / invest * 100 : 0;

  // Cashflow mensuel (hypothèse : IPP)
  const cashflow = loyer - credit - chargesTotal / 12 - impotIPP / 12;

  // DRB = investissement / loyer annuel brut
  const drb = brutAn > 0 ? invest / brutAn : 0;

  return {
    invest: Math.round(invest),
    brutAn: Math.round(brutAn),
    rentBrut: +rentBrut.toFixed(2),
    rentNetIPP: +rentNetIPP.toFixed(2),
    rentNetIsoc: +rentNetIsoc.toFixed(2),
    impotIPP: Math.round(impotIPP),
    impotIsoc: Math.round(impotIsoc),
    chargesTotal: Math.round(chargesTotal),
    precompte: Math.round(precompte),
    cashflow: Math.round(cashflow),
    drb: +drb.toFixed(1),
    netIPP: Math.round(netIPP),
    netIsoc: Math.round(netIsoc),
    gainIsoc: Math.round(netIsoc - netIPP),
  };
}

function communeYield(c) {
  const brutAn = c.loyer * 12;
  const precompte = c.rc * (c.cent / 100);
  const charges = c.loyer * 12 * 0.15 + precompte + c.prix * 0.006;
  const baseIPP = c.rc * 1.4 * 0.6;
  const impotIPP = baseIPP * 0.45;
  const netIPP = brutAn - charges - impotIPP;
  return {
    brutPct: +(brutAn / c.prix * 100).toFixed(2),
    netIPPPct: +(netIPP / c.prix * 100).toFixed(2),
  };
}
const ALL_C = COMMUNES.map(c => ({ ...c, ...communeYield(c) }));

function yieldColor(pct) {
  if (pct >= 5.0) return "#16a34a";
  if (pct >= 4.0) return "#2563eb";
  if (pct >= 3.0) return "#d97706";
  return "#dc2626";
}
function fmt(n) { return new Intl.NumberFormat("fr-BE").format(n); }
function fmtPct(n) { return n.toFixed(2) + " %"; }

// ═══════════════════════════════════════════════════════════════════════════
// UI PRIMITIVES
// ═══════════════════════════════════════════════════════════════════════════
const Btn = ({ children, onClick, variant = "primary", disabled, sm }) => {
  const v = {
    primary: "background:#1A56DB;color:#fff",
    teal:    "background:#047481;color:#fff",
    gold:    "background:#B45309;color:#fff",
    green:   "background:#15803d;color:#fff",
    outline: "background:transparent;color:#60a5fa;border:1px solid #60a5fa",
    ghost:   "background:transparent;color:#9ca3af",
    danger:  "background:#dc2626;color:#fff",
  }[variant] || "";
  return (
    <button
      onClick={onClick} disabled={disabled}
      style={{ padding: sm ? "5px 12px" : "8px 18px", fontSize: sm ? 12 : 14, borderRadius: 6, border: "none", cursor: disabled ? "not-allowed" : "pointer", opacity: disabled ? 0.5 : 1, fontWeight: 600, ...Object.fromEntries(v.split(";").filter(Boolean).map(s => { const [k,...vs]=s.split(":"); return [k.trim().replace(/-([a-z])/g,(_,c)=>c.toUpperCase()), vs.join(":").trim()]; })) }}
    >{children}</button>
  );
};

const Inp = ({ label, value, onChange, type = "number", suffix, hint, min = 0, step = 1 }) => (
  <div style={{ marginBottom: 12 }}>
    <div style={{ fontSize: 11, color: "#9ca3af", marginBottom: 4 }}>{label}</div>
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <input type={type} value={value} min={min} step={step}
        onChange={e => onChange(e.target.value)}
        style={{ flex: 1, background: "#111827", border: "1px solid #374151", borderRadius: 6, padding: "7px 10px", color: "#f9fafb", fontSize: 13, outline: "none" }}
      />
      {suffix && <span style={{ color: "#6b7280", fontSize: 12 }}>{suffix}</span>}
    </div>
    {hint && <div style={{ fontSize: 10, color: "#4b5563", marginTop: 3 }}>{hint}</div>}
  </div>
);

const Sel = ({ label, value, onChange, options }) => (
  <div style={{ marginBottom: 12 }}>
    <div style={{ fontSize: 11, color: "#9ca3af", marginBottom: 4 }}>{label}</div>
    <select value={value} onChange={e => onChange(e.target.value)}
      style={{ width: "100%", background: "#111827", border: "1px solid #374151", borderRadius: 6, padding: "7px 10px", color: "#f9fafb", fontSize: 13, outline: "none" }}
    >
      {options.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
    </select>
  </div>
);

const KPI = ({ label, value, sub, color = "#1A56DB", dark = "#1e3a5f" }) => (
  <div style={{ background: dark, borderTop: `3px solid ${color}`, borderRadius: 8, padding: "12px 10px", textAlign: "center" }}>
    <div style={{ color, fontSize: 22, fontWeight: 700, fontFamily: "Georgia,serif", lineHeight: 1 }}>{value}</div>
    <div style={{ color: "#e5e7eb", fontSize: 11, fontWeight: 600, marginTop: 4 }}>{label}</div>
    {sub && <div style={{ color: "#6b7280", fontSize: 10, marginTop: 2, fontStyle: "italic" }}>{sub}</div>}
  </div>
);

const Tag = ({ children, color = "#1A56DB" }) => (
  <span style={{ background: color + "22", color, border: `1px solid ${color}44`, borderRadius: 4, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>{children}</span>
);

// ═══════════════════════════════════════════════════════════════════════════
// PLAN DEFS
// ═══════════════════════════════════════════════════════════════════════════
const PLANS = {
  free:    { label: "FREE",    price: "0 €",      color: "#047481", calcFull: false, heatLimit: 5,  ugc: false, dash: false },
  starter: { label: "STARTER", price: "9 €/mois", color: "#1A56DB", calcFull: true,  heatLimit: 99, ugc: true,  dash: false },
  pro:     { label: "PRO",     price: "19 €/mois",color: "#6C2BD9", calcFull: true,  heatLimit: 99, ugc: true,  dash: true  },
};

// ═══════════════════════════════════════════════════════════════════════════
// STORAGE HELPERS
// ═══════════════════════════════════════════════════════════════════════════
async function storeGet(key) {
  try { const r = await window.storage.get(key); return r ? JSON.parse(r.value) : null; } catch { return null; }
}
async function storeSet(key, val) {
  try { await window.storage.set(key, JSON.stringify(val)); } catch {}
}

// ═══════════════════════════════════════════════════════════════════════════
// LANDING PAGE
// ═══════════════════════════════════════════════════════════════════════════
function Landing({ onNav }) {
  const features = [
    { icon: "📊", title: "Calculateur financier", desc: "Rendement brut, net IPP, net ISoc, cashflow — en 30 secondes à partir du prix d'achat et du loyer.", cta: "calculator" },
    { icon: "🗺️", title: "Carte de chaleur", desc: "28 communes belges classées par rendement net. Identifiez les zones à fort potentiel locatif en un coup d'œil.", cta: "heatmap" },
    { icon: "📝", title: "Encodage UGC", desc: "Saisissez vos biens, comparez-les entre eux. Les données sont stockées localement et ne sont jamais revendues.", cta: "ugc" },
  ];
  return (
    <div style={{ minHeight: "100vh", background: "linear-gradient(135deg,#0D2137 0%,#0a1929 60%,#071018 100%)" }}>
      {/* Hero */}
      <div style={{ maxWidth: 900, margin: "0 auto", padding: "80px 24px 60px" }}>
        <div style={{ display: "inline-block", background: "#047481", color: "#fff", padding: "4px 14px", borderRadius: 4, fontSize: 11, fontWeight: 700, letterSpacing: 2, marginBottom: 20 }}>
          INVESTISSEMENT IMMOBILIER BELGE
        </div>
        <h1 style={{ fontSize: 52, fontFamily: "Georgia,serif", color: "#fff", margin: "0 0 12px", lineHeight: 1.1 }}>
          ImmoBelRent
        </h1>
        <div style={{ width: 80, height: 4, background: "#D97706", marginBottom: 20, borderRadius: 2 }} />
        <p style={{ fontSize: 20, color: "#D97706", fontStyle: "italic", marginBottom: 12 }}>
          Analysez la rentabilité réelle de tout bien immobilier belge.
        </p>
        <p style={{ fontSize: 15, color: "#8baed4", maxWidth: 560, lineHeight: 1.6, marginBottom: 36 }}>
          Moteur de calcul financier basé sur la fiscalité belge réelle (IPP/ISoc), données
          de marché Statbel et Notaire.be. Zéro bullshit, zéro scraping illégal.
        </p>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          <Btn onClick={() => onNav("calculator")} variant="gold">🧮 Calculer un bien</Btn>
          <Btn onClick={() => onNav("heatmap")} variant="teal">🗺️ Carte de chaleur</Btn>
          <Btn onClick={() => onNav("pricing")} variant="outline">Voir les plans</Btn>
        </div>

        {/* Stats strip */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginTop: 60 }}>
          {[["28+","Communes analysées"],["100%","Données publiques"],["IPP/ISoc","Simulation fiscale"],["UGC","Données partagées"]].map(([v,l]) => (
            <div key={v} style={{ background: "#162035", border: "1px solid #1e3a5f", borderRadius: 8, padding: 20, textAlign: "center" }}>
              <div style={{ fontSize: 22, fontWeight: 700, color: "#D97706", fontFamily: "Georgia,serif" }}>{v}</div>
              <div style={{ fontSize: 11, color: "#8baed4", marginTop: 4 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Features */}
      <div style={{ background: "#0a1929", padding: "60px 24px" }}>
        <div style={{ maxWidth: 900, margin: "0 auto" }}>
          <h2 style={{ color: "#fff", fontFamily: "Georgia,serif", fontSize: 28, marginBottom: 8 }}>Ce que la plateforme calcule</h2>
          <p style={{ color: "#6b7280", fontSize: 14, marginBottom: 40 }}>
            ⚠️ Données de marché basées sur les publications Statbel/Notaire.be — approximées pour le MVP.
            Le calculateur financier utilise la vraie législation fiscale belge 2024.
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 20 }}>
            {features.map(f => (
              <div key={f.cta} style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, padding: 24 }}>
                <div style={{ fontSize: 32, marginBottom: 12 }}>{f.icon}</div>
                <h3 style={{ color: "#f9fafb", fontSize: 16, marginBottom: 8, fontWeight: 700 }}>{f.title}</h3>
                <p style={{ color: "#6b7280", fontSize: 13, lineHeight: 1.5, marginBottom: 16 }}>{f.desc}</p>
                <Btn onClick={() => onNav(f.cta)} variant="ghost" sm>Essayer →</Btn>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// CALCULATOR PAGE
// ═══════════════════════════════════════════════════════════════════════════
function Calculator({ plan, onUpgrade }) {
  const pDef = PLANS[plan];
  const defCommune = ALL_C.find(c => c.id === "LGE");

  const [form, setForm] = useState({
    prixAchat: 185000, loyer: 780, rc: 920, surface: 72,
    centimes: 29, fraisNotaire: 12.5, travaux: 0, credit: 0,
    communeId: "LGE",
  });
  const [res, setRes] = useState(null);
  const [marketC, setMarketC] = useState(defCommune);

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

  // Auto-fill commune data
  const selectCommune = (id) => {
    const c = ALL_C.find(x => x.id === id);
    if (c) {
      setForm(p => ({ ...p, communeId: id, centimes: c.cent }));
      setMarketC(c);
    }
  };

  const calculate = () => {
    const r = calcFinancials(form);
    setRes(r);
  };

  const chartData = res ? [
    { name: "Brut", value: +res.rentBrut.toFixed(2), fill: "#1A56DB" },
    { name: "Net IPP", value: +Math.max(res.rentNetIPP, 0).toFixed(2), fill: "#D97706" },
    { name: "Net ISoc", value: +Math.max(res.rentNetIsoc, 0).toFixed(2), fill: "#15803d" },
  ] : [];

  return (
    <div style={{ maxWidth: 1100, margin: "0 auto", padding: "32px 24px" }}>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ color: "#fff", fontFamily: "Georgia,serif", fontSize: 28, margin: 0 }}>🧮 Calculateur de Rendement</h2>
        <p style={{ color: "#6b7280", fontSize: 13, marginTop: 6 }}>
          Saisissez les données du bien — le moteur calcule automatiquement IPP, ISoc, cashflow et DRB.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 24 }}>
        {/* FORM */}
        <div style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, padding: 20 }}>
          <div style={{ fontSize: 12, color: "#D97706", fontWeight: 700, marginBottom: 16, letterSpacing: 1 }}>DONNÉES DU BIEN</div>

          <Sel label="Commune" value={form.communeId}
            onChange={selectCommune}
            options={ALL_C.map(c => ({ v: c.id, l: `${c.name} (${c.reg})` }))}
          />
          <Inp label="Prix d'achat (€)" value={form.prixAchat} onChange={v => set("prixAchat", v)} suffix="€" />
          <Inp label="Loyer mensuel estimé (€)" value={form.loyer} onChange={v => set("loyer", v)} suffix="€/mois" />
          <Inp label="Surface (m²)" value={form.surface} onChange={v => set("surface", v)} suffix="m²" />
          <Inp label="Revenu Cadastral — RC (€)" value={form.rc} onChange={v => set("rc", v)} suffix="€"
            hint="Visible sur votre extrait cadastral ou avis d'imposition" />

          <div style={{ fontSize: 12, color: "#D97706", fontWeight: 700, margin: "16px 0 12px", letterSpacing: 1 }}>FRAIS & FINANCEMENT</div>
          <Inp label="Frais de notaire (%)" value={form.fraisNotaire} step={0.5} onChange={v => set("fraisNotaire", v)} suffix="%"
            hint="~12.5% ancien bâti · ~3% VEFA" />
          <Inp label="Travaux estimés (€)" value={form.travaux} onChange={v => set("travaux", v)} suffix="€" />
          <Inp label="Mensualité crédit (€)" value={form.credit} onChange={v => set("credit", v)} suffix="€/mois"
            hint="Laisser 0 si achat comptant" />

          <div style={{ marginTop: 8 }}>
            <div style={{ fontSize: 11, color: "#6b7280", marginBottom: 4 }}>
              Centimes additionnels ({form.communeId}) : <strong style={{ color: "#D97706" }}>{form.centimes}</strong>
            </div>
          </div>

          <div style={{ marginTop: 20 }}>
            <Btn onClick={calculate} variant="gold">Calculer →</Btn>
          </div>
        </div>

        {/* RESULTS */}
        <div>
          {!res ? (
            <div style={{ background: "#111827", border: "1px dashed #1f2937", borderRadius: 10, padding: 60, textAlign: "center" }}>
              <div style={{ fontSize: 40, marginBottom: 12 }}>🏠</div>
              <p style={{ color: "#4b5563", fontSize: 14 }}>Saisissez les données et cliquez "Calculer" pour voir l'analyse complète.</p>
              {marketC && (
                <div style={{ marginTop: 20, padding: 16, background: "#0a1929", borderRadius: 8, textAlign: "left", maxWidth: 400, margin: "20px auto 0" }}>
                  <div style={{ fontSize: 11, color: "#D97706", fontWeight: 700, marginBottom: 8 }}>RÉFÉRENCE MARCHÉ — {marketC.name.toUpperCase()}</div>
                  {[["Prix médian 2ch", `${fmt(marketC.prix)} €`],["Loyer médian 2ch", `${marketC.loyer} €/mois`],["Rdmt brut estimé", `${marketC.brutPct} %`],["Rdmt net IPP", `${marketC.netIPPPct} %`]].map(([l,v]) => (
                    <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: "1px solid #1f2937", fontSize: 12 }}>
                      <span style={{ color: "#9ca3af" }}>{l}</span>
                      <span style={{ color: "#f9fafb", fontWeight: 600 }}>{v}</span>
                    </div>
                  ))}
                  <div style={{ fontSize: 10, color: "#4b5563", marginTop: 8 }}>Source: Statbel / Notaire.be (approximations)</div>
                </div>
              )}
            </div>
          ) : (
            <div>
              {/* KPI row */}
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 20 }}>
                <KPI label="Prix de revient total" value={`${fmt(res.invest)} €`} color="#1A56DB" dark="#0f2040" />
                <KPI label="Rendement Brut" value={fmtPct(res.rentBrut)} color="#1A56DB" dark="#0f2040" />
                <KPI label="Rdmt Net IPP" value={fmtPct(res.rentNetIPP)} sub="Personne physique" color="#D97706" dark="#1a1200" />
                <KPI label="Cashflow /mois" value={`${res.cashflow > 0 ? "+" : ""}${fmt(res.cashflow)} €`}
                  color={res.cashflow >= 0 ? "#15803d" : "#dc2626"} dark={res.cashflow >= 0 ? "#0a2010" : "#200a0a"} />
              </div>

              {/* ISoc — gated behind Starter */}
              <div style={{ position: "relative", marginBottom: 20 }}>
                <div style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, padding: 20 }}>
                  <div style={{ fontSize: 12, color: "#15803d", fontWeight: 700, marginBottom: 14 }}>COMPARATIF FISCAL IPP vs ISoc</div>
                  {!pDef.calcFull ? (
                    <div style={{ textAlign: "center", padding: "20px 0", filter: "blur(4px)" }}>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
                        {[["Base imposable","RC × 1.4 − 40%","Loyer − 30% − Amort."],["Impôt annuel","1 820 €","1 050 €"],["Revenu net","28 320 €","31 200 €"],["Rendement net","3.1 %","3.9 %"]].map(([l,a,b]) => (
                          <div key={l} style={{ display: "contents" }}>
                            <div style={{ color: "#9ca3af", fontSize: 11, padding: "4px 0" }}>{l}</div>
                            <div style={{ color: "#D97706", fontSize: 11, fontWeight: 600, padding: "4px 0" }}>{a}</div>
                            <div style={{ color: "#15803d", fontSize: 11, fontWeight: 700, padding: "4px 0" }}>{b}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                  ) : (
                    <div>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0 }}>
                        {[["","IPP (pers. physique)","ISoc (société)"],
                          ["Base imposable", `RC×1.4 − 40% = ${fmt(res.impotIPP / 0.45 / 0.6 * 0.6)} €`, `Loyer − 30% − Amort`],
                          ["Impôt annuel", `${fmt(res.impotIPP)} €`, `${fmt(res.impotIsoc)} €`],
                          ["Revenu net annuel", `${fmt(res.netIPP)} €`, `${fmt(res.netIsoc)} €`],
                          ["Rendement net", fmtPct(res.rentNetIPP), fmtPct(res.rentNetIsoc)],
                          ["Gain ISoc vs IPP", "—", `+${fmt(res.gainIsoc)} €/an`],
                        ].map(([l, a, b], i) => (
                          <div key={i} style={{ display: "contents" }}>
                            <div style={{ fontSize: 11, color: "#6b7280", padding: "6px 8px 6px 0", borderBottom: "1px solid #1f2937", fontWeight: i === 0 ? 700 : 400 }}>{l}</div>
                            <div style={{ fontSize: i === 0 ? 11 : 12, color: i === 0 ? "#D97706" : "#f9fafb", padding: "6px 8px", borderBottom: "1px solid #1f2937", fontWeight: i === 0 ? 700 : 400, background: i === 0 ? "#1a1200" : "transparent" }}>{a}</div>
                            <div style={{ fontSize: i === 0 ? 11 : 12, color: i === 0 ? "#15803d" : b.startsWith("+") ? "#15803d" : "#f9fafb", padding: "6px 8px", borderBottom: "1px solid #1f2937", fontWeight: i === 0 ? 700 : (b.startsWith("+") ? 700 : 400), background: i === 0 ? "#0a2010" : "transparent" }}>{b}</div>
                          </div>
                        ))}
                      </div>
                      <div style={{ marginTop: 12 }}>
                        <KPI label="Rendement Net ISoc" value={fmtPct(res.rentNetIsoc)} sub="Via société (ISoc 25%)" color="#15803d" dark="#0a2010" />
                      </div>
                    </div>
                  )}
                  {!pDef.calcFull && (
                    <div style={{ position: "absolute", inset: 0, background: "rgba(17,24,39,0.92)", borderRadius: 10, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                      <div style={{ fontSize: 28, marginBottom: 8 }}>🔒</div>
                      <div style={{ color: "#f9fafb", fontWeight: 700, marginBottom: 4 }}>Simulation ISoc — Plan Starter</div>
                      <div style={{ color: "#6b7280", fontSize: 12, marginBottom: 16 }}>Découvrez si une société vous fait économiser des impôts</div>
                      <Btn onClick={onUpgrade} variant="gold">Passer au plan Starter →</Btn>
                    </div>
                  )}
                </div>
              </div>

              {/* Chart + details */}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, padding: 20 }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", fontWeight: 700, marginBottom: 12 }}>RENDEMENTS COMPARÉS</div>
                  <ResponsiveContainer width="100%" height={160}>
                    <BarChart data={chartData} barSize={40}>
                      <XAxis dataKey="name" tick={{ fill: "#9ca3af", fontSize: 11 }} axisLine={false} tickLine={false} />
                      <YAxis tick={{ fill: "#9ca3af", fontSize: 10 }} axisLine={false} tickLine={false} unit="%" />
                      <Tooltip formatter={v => [v.toFixed(2) + " %", "Rendement"]} contentStyle={{ background: "#1f2937", border: "none", borderRadius: 6, fontSize: 12 }} />
                      <Bar dataKey="value" radius={[4, 4, 0, 0]}>
                        {chartData.map((d, i) => <Cell key={i} fill={d.fill} />)}
                      </Bar>
                    </BarChart>
                  </ResponsiveContainer>
                </div>
                <div style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, padding: 20 }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", fontWeight: 700, marginBottom: 12 }}>DÉTAIL DES CHARGES</div>
                  {[
                    ["Loyer annuel brut", `${fmt(res.brutAn)} €`, "#1A56DB"],
                    ["Charges annuelles", `−${fmt(res.chargesTotal)} €`, "#D97706"],
                    ["dont précompte imm.", `${fmt(res.precompte)} €`, "#6b7280"],
                    ["Impôt IPP estimé", `−${fmt(res.impotIPP)} €`, "#dc2626"],
                    ["Revenu net IPP", `${fmt(res.netIPP)} €`, "#15803d"],
                    ["DRB (années)", `${res.drb} ans`, "#047481"],
                  ].map(([l, v, c]) => (
                    <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", borderBottom: "1px solid #1f2937", fontSize: 12 }}>
                      <span style={{ color: "#9ca3af" }}>{l}</span>
                      <span style={{ color: c, fontWeight: 600 }}>{v}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// HEATMAP PAGE
// ═══════════════════════════════════════════════════════════════════════════
function Heatmap({ plan, onUpgrade }) {
  const pDef = PLANS[plan];
  const [sort, setSort] = useState("netIPPPct");
  const [filterReg, setFilterReg] = useState("ALL");
  const [selected, setSelected] = useState(null);

  const sorted = useMemo(() => {
    let d = filterReg === "ALL" ? ALL_C : ALL_C.filter(c => c.reg === filterReg);
    return [...d].sort((a, b) => b[sort] - a[sort]);
  }, [sort, filterReg]);

  const visible = pDef.heatLimit >= 99 ? sorted : sorted.slice(0, pDef.heatLimit);
  const locked = pDef.heatLimit < 99;

  const selC = selected ? ALL_C.find(c => c.id === selected) : null;

  return (
    <div style={{ maxWidth: 1100, margin: "0 auto", padding: "32px 24px" }}>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ color: "#fff", fontFamily: "Georgia,serif", fontSize: 28, margin: 0 }}>🗺️ Carte de Chaleur des Marchés</h2>
        <p style={{ color: "#6b7280", fontSize: 13, marginTop: 6 }}>
          Communes classées par rendement net IPP. Source: Statbel / Notaire.be (approximations open data).
          {locked && <span style={{ color: "#D97706" }}> · Limité aux 5 premières communes — <button onClick={onUpgrade} style={{ background: "none", border: "none", color: "#D97706", cursor: "pointer", textDecoration: "underline", fontSize: 13 }}>Passer à Starter pour voir toutes</button></span>}
        </p>
      </div>

      {/* Controls */}
      <div style={{ display: "flex", gap: 12, marginBottom: 20, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 6 }}>
          {["ALL","FL","WAL","BXL"].map(r => (
            <Btn key={r} onClick={() => setFilterReg(r)} variant={filterReg === r ? "primary" : "ghost"} sm>
              {r === "ALL" ? "🇧🇪 Toutes" : r}
            </Btn>
          ))}
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Btn onClick={() => setSort("netIPPPct")} variant={sort === "netIPPPct" ? "gold" : "ghost"} sm>Rdmt net IPP</Btn>
          <Btn onClick={() => setSort("brutPct")} variant={sort === "brutPct" ? "gold" : "ghost"} sm>Rdmt brut</Btn>
          <Btn onClick={() => setSort("loyer")} variant={sort === "loyer" ? "gold" : "ghost"} sm>Loyer</Btn>
          <Btn onClick={() => setSort("prix")} variant={sort === "prix" ? "gold" : "ghost"} sm>Prix</Btn>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: selC ? "1fr 300px" : "1fr", gap: 20 }}>
        {/* Grid heatmap */}
        <div>
          {/* Visual grid */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 20 }}>
            {visible.map((c, i) => {
              const col = yieldColor(c.netIPPPct);
              const isSelected = selected === c.id;
              return (
                <div key={c.id} onClick={() => setSelected(isSelected ? null : c.id)}
                  style={{ width: 82, height: 82, background: col + "22", border: `2px solid ${isSelected ? "#fff" : col}`, borderRadius: 8, padding: 8, cursor: "pointer", position: "relative", transition: "all 0.15s" }}>
                  <div style={{ position: "absolute", top: 4, right: 6, fontSize: 10, color: "#9ca3af" }}>#{i + 1}</div>
                  <div style={{ fontSize: 10, color: "#f9fafb", fontWeight: 700, lineHeight: 1.2 }}>{c.name}</div>
                  <div style={{ fontSize: 14, color: col, fontWeight: 700, marginTop: 4, fontFamily: "Georgia,serif" }}>{c.netIPPPct}%</div>
                  <div style={{ fontSize: 9, color: "#6b7280", marginTop: 2 }}>{c.reg}</div>
                </div>
              );
            })}
            {locked && (
              <div onClick={onUpgrade} style={{ width: 82, height: 82, background: "#1f2937", border: "2px dashed #374151", borderRadius: 8, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
                <div style={{ fontSize: 20 }}>🔒</div>
                <div style={{ fontSize: 9, color: "#6b7280", textAlign: "center", marginTop: 4 }}>{sorted.length - 5} autres communes</div>
              </div>
            )}
          </div>

          {/* Legend */}
          <div style={{ display: "flex", gap: 16, marginBottom: 20 }}>
            {[["≥ 5%","#16a34a","Excellent"],["≥ 4%","#2563eb","Bon"],["≥ 3%","#d97706","Moyen"],["< 3%","#dc2626","Faible"]].map(([l,c,d]) => (
              <div key={l} style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <div style={{ width: 16, height: 16, background: c, borderRadius: 3 }} />
                <span style={{ fontSize: 11, color: "#9ca3af" }}>{l} — {d}</span>
              </div>
            ))}
          </div>

          {/* Table */}
          <div style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, overflow: "hidden" }}>
            <div style={{ display: "grid", gridTemplateColumns: "28px 1fr 60px 70px 75px 75px 55px 60px", gap: 0 }}>
              {["#","Commune","Région","Prix médian","Loyer/mois","Rdmt brut","Rdmt net","Trend"].map(h => (
                <div key={h} style={{ padding: "10px 8px", background: "#0D2137", fontSize: 10, color: "#6b7280", fontWeight: 700, borderBottom: "1px solid #1f2937" }}>{h}</div>
              ))}
              {visible.map((c, i) => {
                const col = yieldColor(c.netIPPPct);
                return [
                  <div key={`${c.id}-n`} style={{ padding: "9px 8px", fontSize: 11, color: "#4b5563", borderBottom: "1px solid #111827", cursor: "pointer" }} onClick={() => setSelected(c.id === selected ? null : c.id)}>{i + 1}</div>,
                  <div key={`${c.id}-name`} style={{ padding: "9px 8px", fontSize: 12, color: "#f9fafb", fontWeight: 600, borderBottom: "1px solid #111827", cursor: "pointer" }} onClick={() => setSelected(c.id === selected ? null : c.id)}>{c.name}</div>,
                  <div key={`${c.id}-reg`} style={{ padding: "9px 8px", borderBottom: "1px solid #111827" }}><Tag color={c.reg === "FL" ? "#1A56DB" : c.reg === "WAL" ? "#047481" : "#6C2BD9"}>{c.reg}</Tag></div>,
                  <div key={`${c.id}-prix`} style={{ padding: "9px 8px", fontSize: 11, color: "#d1d5db", borderBottom: "1px solid #111827" }}>{fmt(c.prix)} €</div>,
                  <div key={`${c.id}-loyer`} style={{ padding: "9px 8px", fontSize: 11, color: "#d1d5db", borderBottom: "1px solid #111827" }}>{c.loyer} €</div>,
                  <div key={`${c.id}-brut`} style={{ padding: "9px 8px", fontSize: 12, color: "#1A56DB", fontWeight: 600, borderBottom: "1px solid #111827" }}>{c.brutPct}%</div>,
                  <div key={`${c.id}-net`} style={{ padding: "9px 8px", fontSize: 12, color: col, fontWeight: 700, borderBottom: "1px solid #111827" }}>{c.netIPPPct}%</div>,
                  <div key={`${c.id}-trend`} style={{ padding: "9px 8px", fontSize: 12, color: c.trend > 0 ? "#15803d" : c.trend < 0 ? "#dc2626" : "#6b7280", borderBottom: "1px solid #111827" }}>
                    {c.trend > 0 ? `↗ +${c.trend}` : c.trend < 0 ? `↘ ${c.trend}` : "→ 0"}
                  </div>,
                ];
              })}
            </div>
          </div>
        </div>

        {/* Selected commune panel */}
        {selC && (
          <div style={{ background: "#111827", border: `2px solid ${yieldColor(selC.netIPPPct)}`, borderRadius: 10, padding: 20, alignSelf: "start" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start", marginBottom: 16 }}>
              <div>
                <h3 style={{ color: "#fff", fontSize: 20, fontFamily: "Georgia,serif", margin: 0 }}>{selC.name}</h3>
                <div style={{ color: "#6b7280", fontSize: 12 }}>{selC.prov} · {selC.reg}</div>
              </div>
              <button onClick={() => setSelected(null)} style={{ background: "none", border: "none", color: "#6b7280", cursor: "pointer", fontSize: 18 }}>✕</button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 16 }}>
              <KPI label="Rdmt net IPP" value={`${selC.netIPPPct}%`} color={yieldColor(selC.netIPPPct)} dark="#0a1929" />
              <KPI label="Rdmt brut" value={`${selC.brutPct}%`} color="#1A56DB" dark="#0a1929" />
            </div>
            {[["Prix médian 2ch", `${fmt(selC.prix)} €`], ["Loyer médian 2ch", `${selC.loyer} €/mois`], ["Revenu Cadastral (moy.)", `${selC.rc} €`], ["Centimes additionnels", selC.cent.toString()], ["Population", fmt(selC.pop)], ["Tendance prix", selC.trend > 0 ? `↗ +${selC.trend}% /an` : selC.trend < 0 ? `↘ ${selC.trend}% /an` : "→ Stable"]].map(([l, v]) => (
              <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", borderBottom: "1px solid #1f2937", fontSize: 12 }}>
                <span style={{ color: "#9ca3af" }}>{l}</span>
                <span style={{ color: "#f9fafb", fontWeight: 600 }}>{v}</span>
              </div>
            ))}
            <div style={{ marginTop: 16 }}>
              <div style={{ fontSize: 10, color: "#4b5563", lineHeight: 1.5 }}>
                ⚠️ Données approximées — Statbel baromètre immobilier + Notaire.be publications trimestrielles. Les valeurs réelles peuvent différer selon le type de bien et l'état du marché local.
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// UGC FORM PAGE
// ═══════════════════════════════════════════════════════════════════════════
function UGCPage({ plan, properties, onAdd, onDelete, onUpgrade }) {
  const pDef = PLANS[plan];
  const [form, setForm] = useState({ adresse: "", commune: "LGE", type: "APT", surface: "", prixAchat: "", loyer: "", rc: "", fraisNotaire: "12.5", travaux: "0", credit: "0", note: "" });
  const [saved, setSaved] = useState(false);

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

  const submit = () => {
    if (!form.prixAchat || !form.loyer) return;
    const c = ALL_C.find(x => x.id === form.commune);
    const calc = calcFinancials({ ...form, centimes: c?.cent || 25 });
    const prop = {
      id: Date.now().toString(),
      date: new Date().toLocaleDateString("fr-BE"),
      ...form, communeName: c?.name || form.commune,
      ...calc,
    };
    onAdd(prop);
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
    setForm({ adresse: "", commune: form.commune, type: "APT", surface: "", prixAchat: "", loyer: "", rc: "", fraisNotaire: "12.5", travaux: "0", credit: "0", note: "" });
  };

  return (
    <div style={{ maxWidth: 1100, margin: "0 auto", padding: "32px 24px" }}>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ color: "#fff", fontFamily: "Georgia,serif", fontSize: 28, margin: 0 }}>📝 Encoder un Bien (UGC)</h2>
        <p style={{ color: "#6b7280", fontSize: 13, marginTop: 6 }}>
          Vos biens sont sauvegardés localement. Les données ne sont jamais envoyées à un serveur tiers.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "350px 1fr", gap: 24 }}>
        {/* Form */}
        <div style={{ position: "relative" }}>
          <div style={{ background: "#111827", border: "1px solid #1f2937", borderRadius: 10, padding: 20 }}>
            <div style={{ fontSize: 12, color: "#D97706", fontWeight: 700, marginBottom: 16 }}>NOUVEAU BIEN</div>
            <Inp label="Adresse" value={form.adresse} onChange={v => set("adresse", v)} type="text" />
            <Sel label="Commune" value={form.commune} onChange={v => set("commune", v)} options={ALL_C.map(c => ({ v: c.id, l: `${c.name} (${c.reg})` }))} />
            <Sel label="Type de bien" value={form.type} onChange={v => set("type", v)} options={[{v:"APT",l:"Appartement"},{v:"MAI",l:"Maison"},{v:"STU",l:"Studio"},{v:"GAR",l:"Garage/Box"},{v:"COM",l:"Commercial"}]} />
            <Inp label="Surface (m²)" value={form.surface} onChange={v => set("surface", v)} />
            <Inp label="Prix d'achat (€)" value={form.prixAchat} onChange={v => set("prixAchat", v)} />
            <Inp label="Loyer mensuel (€)" value={form.loyer} onChange={v => set("loyer", v)} />
            <Inp label="Revenu Cadastral RC (€)" value={form.rc} onChange={v => set("rc", v)} />
            <Inp label="Frais notaire (%)" value={form.fraisNotaire} step={0.5} onChange={v => set("fraisNotaire", v)} />
            <Inp label="Travaux (€)" value={form.travaux} onChange={v => set("travaux", v)} />
            <Inp label="Crédit mensuel (€)" value={form.credit} onChange={v => set("credit", v)} />
            <div style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 11, color: "#9ca3af", marginBottom: 4 }}>Notes personnelles</div>
              <textarea value={form.note} onChange={e => set("note", e.target.value)} rows={2}
                style={{ width: "100%", background: "#111827", border: "1px solid #374151", borderRadius: 6, padding: "7px 10px", color: "#f9fafb", fontSize: 13, resize: "none", outline: "none", boxSizing: "border-box" }} />
            </div>
            {saved && <div style={{ background: "#0a2010", border: "1px solid #15803d", borderRadius: 6, padding: "8px 12px", color: "#15803d", fontSize: 12, marginBottom: 12 }}>✓ Bien enregistré avec succès</div>}
            <Btn onClick={submit} variant="teal" disabled={!pDef.ugc || !form.prixAchat || !form.loyer}>Enregistrer le bien</Btn>
          </div>
          {!pDef.ugc && (
            <div style={{ position: "absolute", inset: 0, background: "rgba(17,24,39,0.93)", borderRadius: 10, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
              <div style={{ fontSize: 32, marginBottom: 12 }}>🔒</div>
              <div style={{ color: "#fff", fontWeight: 700, marginBottom: 4 }}>Fonctionnalité Starter</div>
              <div style={{ color: "#6b7280", fontSize: 12, marginBottom: 16, textAlign: "center", maxWidth: 200 }}>L'encodage UGC est disponible dès le plan Starter (9 €/mois)</div>
              <Btn onClick={onUpgrade} variant="gold">Passer à Starter →</Btn>
            </div>
          )}
        </div>

        {/* Property list */}
        <div>
          <div style={{ fontSize: 12, color: "#9ca3af", fontWeight: 700, marginBottom: 16 }}>MES BIENS ENCODÉS ({properties.length})</div>
          {properties.length === 0 ? (
            <div style={{ background: "#111827", border: "1px dashed #1f2937", borderRadius: 10, padding: 40, textAlign: "center" }}>
              <div style={{ fontSize: 36, marginBottom: 12 }}>🏠</div>
              <p style={{ color: "#4b5563", fontSize: 14 }}>Aucun bien encodé. Remplissez le formulaire pour commencer.</p>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {properties.map(p => {
                const col = yieldColor(p.rentNetIPP || 0);
                return (
                  <div key={p.id} style={{ background: "#111827", border: `1px solid #1f2937`, borderLeft: `4px solid ${col}`, borderRadius: 8, padding: 16 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
                      <div>
                        <div style={{ color: "#f9fafb", fontWeight: 700, fontSize: 14 }}>{p.adresse || "Sans adresse"}</div>
                        <div style={{ color: "#6b7280", fontSize: 12 }}>{p.communeName} · {p.type} · {p.surface} m² · {p.date}</div>
                      </div>
                      <button onClick={() => onDelete(p.id)} style={{ background: "none", border: "none", color: "#4b5563", cursor: "pointer", fontSize: 16, padding: 4 }}>🗑</button>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 8, marginTop: 12 }}>
                      {[
                        ["Prix de revient", `${fmt(p.invest || 0)} €`, "#1A56DB"],
                        ["Loyer", `${p.loyer} €/mois`, "#9ca3af"],
                        ["Rdmt brut", `${p.rentBrut || 0}%`, "#1A56DB"],
                        ["Rdmt net IPP", `${p.rentNetIPP || 0}%`, col],
                        ["Cashflow", `${p.cashflow >= 0 ? "+" : ""}${p.cashflow || 0} €`, p.cashflow >= 0 ? "#15803d" : "#dc2626"],
                      ].map(([l, v, c]) => (
                        <div key={l} style={{ textAlign: "center" }}>
                          <div style={{ fontSize: 13, color: c, fontWeight: 700, fontFamily: "Georgia,serif" }}>{v}</div>
                          <div style={{ fontSize: 10, color: "#4b5563", marginTop: 2 }}>{l}</div>
                        </div>
                      ))}
                    </div>
                    {p.note && <div style={{ marginTop: 8, fontSize: 11, color: "#6b7280", fontStyle: "italic" }}>📝 {p.note}</div>}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// PRICING PAGE
// ═══════════════════════════════════════════════════════════════════════════
function Pricing({ plan, onChangePlan }) {
  const rows = [
    ["Calculateur rendement brut",   true,  true,  true ],
    ["Simulation ISoc (vs IPP)",      false, true,  true ],
    ["Heatmap toutes communes (28)", false, true,  true ],
    ["Encodage UGC biens",           false, true,  true ],
    ["Export PDF analyse",           false, true,  true ],
    ["Alertes email",                false, false, true ],
    ["Dashboard portefeuille",       false, false, true ],
    ["Accès API (500 calls/mois)",   false, false, true ],
    ["Support prioritaire",          false, false, true ],
  ];
  const plans = [
    { id: "free",    name: "FREE",    price: "0 €",      freq: "",          color: "#047481", desc: "Découverte" },
    { id: "starter", name: "STARTER", price: "9 €",      freq: "/mois",     color: "#1A56DB", desc: "Investisseur débutant", popular: false },
    { id: "pro",     name: "PRO",     price: "19 €",     freq: "/mois",     color: "#6C2BD9", desc: "Investisseur actif", popular: true },
  ];

  return (
    <div style={{ maxWidth: 900, margin: "0 auto", padding: "32px 24px" }}>
      <div style={{ textAlign: "center", marginBottom: 40 }}>
        <h2 style={{ color: "#fff", fontFamily: "Georgia,serif", fontSize: 32, margin: "0 0 8px" }}>Plans & Tarifs</h2>
        <p style={{ color: "#6b7280", fontSize: 14 }}>Commencez gratuitement. Passez au plan supérieur quand vous en avez besoin.</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginBottom: 40 }}>
        {plans.map(p => (
          <div key={p.id} style={{ background: "#111827", border: `2px solid ${plan === p.id ? p.color : "#1f2937"}`, borderRadius: 12, overflow: "hidden", position: "relative" }}>
            {p.popular && <div style={{ background: "#D97706", color: "#fff", fontSize: 10, fontWeight: 700, textAlign: "center", padding: "4px 0", letterSpacing: 1 }}>⭐ POPULAIRE</div>}
            <div style={{ background: p.color, padding: "20px 20px 16px" }}>
              <div style={{ color: "#fff", fontWeight: 800, fontSize: 18 }}>{p.name}</div>
              <div style={{ color: "rgba(255,255,255,0.7)", fontSize: 12 }}>{p.desc}</div>
              <div style={{ marginTop: 8 }}>
                <span style={{ color: "#fff", fontSize: 32, fontFamily: "Georgia,serif", fontWeight: 700 }}>{p.price}</span>
                <span style={{ color: "rgba(255,255,255,0.6)", fontSize: 13 }}>{p.freq}</span>
              </div>
            </div>
            <div style={{ padding: 20 }}>
              {rows.map(([feat, f, s, pr]) => {
                const included = p.id === "free" ? f : p.id === "starter" ? s : pr;
                return (
                  <div key={feat} style={{ display: "flex", alignItems: "center", gap: 8, padding: "5px 0", fontSize: 12 }}>
                    <span style={{ color: included ? "#15803d" : "#374151", fontSize: 14 }}>{included ? "✓" : "✕"}</span>
                    <span style={{ color: included ? "#d1d5db" : "#4b5563" }}>{feat}</span>
                  </div>
                );
              })}
              <div style={{ marginTop: 20 }}>
                {plan === p.id ? (
                  <div style={{ background: p.color + "22", border: `1px solid ${p.color}`, borderRadius: 6, padding: "8px 16px", textAlign: "center", fontSize: 13, color: p.color, fontWeight: 700 }}>Plan actuel ✓</div>
                ) : (
                  <Btn onClick={() => onChangePlan(p.id)} variant={p.id === "pro" ? "primary" : "outline"}>
                    {p.id === "free" ? "Rétrograder" : `Choisir ${p.name}`}
                  </Btn>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ background: "#0a1929", border: "1px solid #1e3a5f", borderRadius: 10, padding: 24 }}>
        <div style={{ fontSize: 13, color: "#D97706", fontWeight: 700, marginBottom: 12 }}>⚠️ NOTE MVP — HONNÊTETÉ TOTALE</div>
        <p style={{ color: "#6b7280", fontSize: 13, lineHeight: 1.6, margin: 0 }}>
          Cette démo simule les plans Freemium. Dans la version production, les paiements seraient traités via Stripe.
          Les données de marché (prix médians, loyers) sont des <strong style={{ color: "#9ca3af" }}>approximations</strong> basées sur les publications open data
          Statbel et Notaire.be — elles ne constituent pas des conseils financiers.
          Le calculateur fiscal utilise la vraie législation belge 2024 mais consultez votre comptable pour toute décision réelle.
        </p>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// MAIN APP
// ═══════════════════════════════════════════════════════════════════════════
export default function App() {
  const [view, setView] = useState("landing");
  const [plan, setPlan] = useState("free");
  const [properties, setProperties] = useState([]);
  const [toast, setToast] = useState(null);

  // Load persisted data on mount
  useEffect(() => {
    storeGet("immobelrent:plan").then(p => { if (p) setPlan(p); });
    storeGet("immobelrent:properties").then(ps => { if (ps) setProperties(ps); });
  }, []);

  const changePlan = async (p) => {
    setPlan(p);
    await storeSet("immobelrent:plan", p);
    showToast(`Plan ${PLANS[p].label} activé ✓`, "#15803d");
  };

  const addProp = async (prop) => {
    const next = [prop, ...properties];
    setProperties(next);
    await storeSet("immobelrent:properties", next);
  };

  const delProp = async (id) => {
    const next = properties.filter(p => p.id !== id);
    setProperties(next);
    await storeSet("immobelrent:properties", next);
  };

  const showToast = (msg, color = "#1A56DB") => {
    setToast({ msg, color });
    setTimeout(() => setToast(null), 3000);
  };

  const goUpgrade = () => {
    setView("pricing");
    showToast("Choisissez un plan pour débloquer cette fonctionnalité", "#D97706");
  };

  const pDef = PLANS[plan];
  const navItems = [
    { id: "calculator", label: "🧮 Calculateur" },
    { id: "heatmap",    label: "🗺️ Heatmap" },
    { id: "ugc",        label: "📝 Mes biens" },
    { id: "pricing",    label: "💳 Plans" },
  ];

  return (
    <div style={{ minHeight: "100vh", background: "#0a1929", color: "#f9fafb", fontFamily: "system-ui,-apple-system,sans-serif" }}>
      {/* Navbar */}
      <nav style={{ background: "#0D2137", borderBottom: "1px solid #1e3a5f", padding: "0 24px", position: "sticky", top: 0, zIndex: 50, display: "flex", alignItems: "center", height: 56 }}>
        <button onClick={() => setView("landing")} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", alignItems: "center", gap: 8, marginRight: 32 }}>
          <div style={{ width: 28, height: 28, background: "#D97706", borderRadius: 6, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>🏠</div>
          <span style={{ color: "#fff", fontWeight: 800, fontSize: 16, fontFamily: "Georgia,serif" }}>ImmoBelRent</span>
        </button>
        <div style={{ display: "flex", gap: 4, flex: 1 }}>
          {navItems.map(n => (
            <button key={n.id} onClick={() => setView(n.id)}
              style={{ background: view === n.id ? "#1e3a5f" : "none", border: "none", color: view === n.id ? "#fff" : "#9ca3af", padding: "6px 14px", borderRadius: 6, cursor: "pointer", fontSize: 13, fontWeight: view === n.id ? 600 : 400 }}>
              {n.label}
            </button>
          ))}
        </div>
        {/* Plan badge */}
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, background: pDef.color + "22", border: `1px solid ${pDef.color}44`, borderRadius: 20, padding: "4px 12px" }}>
            <div style={{ width: 8, height: 8, borderRadius: "50%", background: pDef.color }} />
            <span style={{ fontSize: 12, color: pDef.color, fontWeight: 700 }}>{pDef.label}</span>
            <span style={{ fontSize: 11, color: "#6b7280" }}>{pDef.price}</span>
          </div>
          {plan === "free" && <Btn onClick={() => setView("pricing")} variant="gold" sm>Upgrader</Btn>}
        </div>
      </nav>

      {/* Content */}
      <main>
        {view === "landing"     && <Landing onNav={setView} />}
        {view === "calculator"  && <Calculator plan={plan} onUpgrade={goUpgrade} />}
        {view === "heatmap"     && <Heatmap plan={plan} onUpgrade={goUpgrade} />}
        {view === "ugc"         && <UGCPage plan={plan} properties={properties} onAdd={addProp} onDelete={delProp} onUpgrade={goUpgrade} />}
        {view === "pricing"     && <Pricing plan={plan} onChangePlan={changePlan} />}
      </main>

      {/* Toast */}
      {toast && (
        <div style={{ position: "fixed", bottom: 24, right: 24, background: toast.color, color: "#fff", padding: "12px 20px", borderRadius: 8, fontSize: 13, fontWeight: 600, zIndex: 100, boxShadow: "0 4px 20px rgba(0,0,0,0.4)" }}>
          {toast.msg}
        </div>
      )}

      {/* Footer disclaimer */}
      <div style={{ background: "#060e1c", borderTop: "1px solid #1e3a5f", padding: "16px 24px", textAlign: "center" }}>
        <p style={{ color: "#374151", fontSize: 11, margin: 0 }}>
          ImmoBelRent MVP — OOND SRL 2026 · Données de marché: Statbel / Notaire.be (approximations) · Fiscalité: législation BE 2024 · Ne constitue pas un conseil financier ou fiscal.
        </p>
      </div>
    </div>
  );
}
