// Rentability simulator — interactive section for Direction C.
// Inputs: land price, land surface, COS, rent.
// Number of 37 m² apts is DERIVED from landSurface × COS ÷ 37 (no user input).
// Outputs: gross yield, payback, cost breakdown, derived unit count.

function Simulator() {
  const { INK, INK_SOFT, INK_FAINT, PAPER, PAPER_DEEP } = window.WF;
  const ACCENT = '#d49328';
  const WARN = '#c84a26';
  const mono = { fontFamily: 'ui-monospace, "SF Mono", monospace', fontSize: 11, color: INK_SOFT, letterSpacing: '.04em' };

  const [landPrice, setLandPrice] = React.useState(150000);
  const [landSurface, setLandSurface] = React.useState(500);
  const [cos, setCos] = React.useState(0.5);
  const [rentPerApt, setRentPerApt] = React.useState(850);

  const APT_SURFACE = 37;          // m² per apt
  const COST_PER_UNIT = 25000;     // €/unit · all-inclusive (VRD, micro-pieux, études sol & structure)

  const buildableSurface = landSurface * cos;
  const numApts = Math.max(0, Math.floor(buildableSurface / APT_SURFACE));
  const usedSurface = numApts * APT_SURFACE;
  const surfaceUtilization = buildableSurface > 0 ? (usedSurface / buildableSurface) * 100 : 0;
  const tooSmall = numApts === 0;

  const constructionCost = numApts * COST_PER_UNIT;
  const totalInvestment = landPrice + constructionCost;
  const monthlyRent = numApts * rentPerApt;
  const annualRent = monthlyRent * 12;
  const grossYield = totalInvestment > 0 && numApts > 0 ? (annualRent / totalInvestment) * 100 : 0;
  const paybackYears = annualRent > 0 ? totalInvestment / annualRent : Infinity;

  const fmtEUR = (n) => Math.round(n).toLocaleString('fr-FR').replace(/ | /g, ' ') + ' €';
  const fmtNum = (n) => Math.round(n).toLocaleString('fr-FR').replace(/,/g, ' ');

  // Sketchy slider
  function Slider({ label, unit, value, onChange, min, max, step = 1, fmt = fmtNum }) {
    const pct = ((value - min) / (max - min)) * 100;
    return (
      <div style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
          <span style={{ ...mono, fontSize: 10 }}>{label}</span>
          <span style={{ fontFamily: "'Caveat', cursive", fontSize: 26, color: ACCENT, lineHeight: 1, fontWeight: 700 }}>
            {fmt(value)}<span style={{ ...mono, fontSize: 11, marginLeft: 4, color: INK_SOFT }}>{unit}</span>
          </span>
        </div>
        <div style={{ position: 'relative', height: 24, display: 'flex', alignItems: 'center' }}>
          <input
            type="range" min={min} max={max} step={step} value={value}
            onChange={(e) => onChange(parseFloat(e.target.value))}
            style={{ position: 'absolute', inset: 0, width: '100%', opacity: 0, cursor: 'pointer', zIndex: 2, margin: 0 }}
          />
          <div style={{ position: 'absolute', left: 0, right: 0, height: 2, background: INK_FAINT }}></div>
          <div style={{ position: 'absolute', left: 0, width: `${pct}%`, height: 2, background: ACCENT }}></div>
          <div style={{ position: 'absolute', left: `calc(${pct}% - 8px)`, width: 16, height: 16, background: ACCENT, border: `1.6px solid ${INK}`, pointerEvents: 'none' }}></div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', ...mono, fontSize: 9, marginTop: 4 }}>
          <span>{fmt(min)}</span>
          <span>{fmt(max)}</span>
        </div>
      </div>
    );
  }

  return (
    <section id="simulator" className="s-section" style={{ marginBottom: 90, position: 'relative' }}>
      {/* Section title — same dossier style as other §s */}
      <div className="s-section-title" style={{ display: 'flex', alignItems: 'baseline', gap: 18, borderBottom: `1px solid ${INK}`, paddingBottom: 12, marginBottom: 28 }}>
        <span style={{ ...mono, color: ACCENT, fontSize: 13 }}>§ 06 · Simulateur</span>
        <span className="s-section-display" style={{ fontFamily: "'Caveat', cursive", fontSize: 38, fontWeight: 700, color: INK, lineHeight: 1 }}>Simulateur de rentabilité</span>
        <span className="s-section-title-sub" style={{ marginLeft: 'auto', ...mono, fontSize: 11 }}>● live · déplacez les sliders</span>
      </div>

      <div className="s-sim-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 28, alignItems: 'flex-start' }}>
        {/* ── INPUTS ── */}
        <Box padding={22} label="ENTRÉES">
          <Slider label="PRIX DU TERRAIN" unit="" min={20000} max={300000} step={5000} value={landPrice} onChange={setLandPrice} fmt={fmtEUR} />
          <Slider label="SURFACE DU TERRAIN" unit="m²" min={100} max={4000} step={10} value={landSurface} onChange={setLandSurface} />
          <Slider label="COS · COEFFICIENT D'OCCUPATION" unit="×" min={0.1} max={1} step={0.1} value={cos} onChange={setCos} fmt={(v) => v.toFixed(1).replace('.', ',')} />
          <Slider label="LOYER MENSUEL / LOGEMENT" unit="" min={400} max={1200} step={10} value={rentPerApt} onChange={setRentPerApt} fmt={fmtEUR} />
          <div style={{ marginTop: 8, padding: 10, borderTop: `1px dashed ${INK_FAINT}`, ...mono, fontSize: 10 }}>
            HYPOTHÈSE · 37 m² / unité · 25 000 € / unité tout compris (VRD, micro-pieux, études sol & structure)<br/>
            Nombre de logements <span style={{ color: ACCENT }}>auto-calculé</span> à partir de surface × COS ÷ 37 m².
          </div>
        </Box>

        {/* ── OUTPUTS ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* ── Derivation banner — makes the COS → unit count chain explicit ── */}
          <Box padding={20} label="ÉTAPE 1 · LOGEMENTS POSSIBLES" style={{ borderColor: tooSmall ? WARN : INK }}>
            <div className="s-sim-chain" style={{ display: 'grid', gridTemplateColumns: 'auto auto auto auto auto 1fr', gap: 14, alignItems: 'baseline', fontFamily: "'Caveat', cursive", fontWeight: 700 }}>
              <div>
                <div style={{ ...mono, fontSize: 9 }}>SURFACE</div>
                <div style={{ fontSize: 26, color: INK, lineHeight: 1 }}>{fmtNum(landSurface)}<span style={{ ...mono, fontSize: 10, color: INK_SOFT, marginLeft: 2 }}>m²</span></div>
              </div>
              <div style={{ ...mono, fontSize: 18, color: INK_FAINT, alignSelf: 'center' }}>×</div>
              <div>
                <div style={{ ...mono, fontSize: 9 }}>COS</div>
                <div style={{ fontSize: 26, color: INK, lineHeight: 1 }}>{cos.toFixed(1).replace('.', ',')}</div>
              </div>
              <div style={{ ...mono, fontSize: 18, color: INK_FAINT, alignSelf: 'center' }}>÷</div>
              <div>
                <div style={{ ...mono, fontSize: 9 }}>UNITÉ</div>
                <div style={{ fontSize: 26, color: INK, lineHeight: 1 }}>37<span style={{ ...mono, fontSize: 10, color: INK_SOFT, marginLeft: 2 }}>m²</span></div>
              </div>
              <div style={{ borderLeft: `1.4px solid ${INK_FAINT}`, paddingLeft: 18 }}>
                <div style={{ ...mono, fontSize: 9, color: tooSmall ? WARN : ACCENT }}>{tooSmall ? '⚠ SURFACE TROP PETITE' : '= LOGEMENTS'}</div>
                <div style={{ fontSize: 56, color: tooSmall ? WARN : ACCENT, lineHeight: 1, marginTop: 2 }}>
                  {numApts}<span style={{ ...mono, fontSize: 11, color: INK_SOFT, marginLeft: 6 }}>{numApts === 1 ? 'logement' : 'logements'}</span>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 14, height: 6, border: `1.2px solid ${INK}` }}>
              <div style={{ width: `${Math.min(surfaceUtilization, 100)}%`, height: '100%', background: tooSmall ? WARN : ACCENT }}></div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', ...mono, fontSize: 9, marginTop: 4 }}>
              <span>{fmtNum(usedSurface)} m² occupés</span>
              <span>{fmtNum(buildableSurface)} m² constructibles · {surfaceUtilization.toFixed(0)}% rempli</span>
            </div>
          </Box>

          {/* ── Cost breakdown — per-unit math made explicit ── */}
          <Box padding={20} label="ÉTAPE 2 · RÉPARTITION DES COÛTS">
            <div className="s-sim-cost-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
              <div>
                <div style={{ ...mono, fontSize: 10 }}>TERRAIN</div>
                <div style={{ fontFamily: "'Caveat', cursive", fontSize: 32, color: INK, marginTop: 4, fontWeight: 700 }}>{fmtEUR(landPrice)}</div>
                <div style={{ ...mono, fontSize: 9, marginTop: 2, color: INK_SOFT }}>achat foncier</div>
              </div>
              <div>
                <div style={{ ...mono, fontSize: 10 }}>CONSTRUCTION</div>
                <div style={{ fontFamily: "'Caveat', cursive", fontSize: 32, color: INK, marginTop: 4, fontWeight: 700 }}>{fmtEUR(constructionCost)}</div>
                <div style={{ ...mono, fontSize: 9, marginTop: 2, color: INK_SOFT }}>{numApts} × 25 000 € tout inclus</div>
              </div>
              <div>
                <div style={{ ...mono, fontSize: 10, color: ACCENT }}>= TOTAL</div>
                <div style={{ fontFamily: "'Caveat', cursive", fontSize: 32, color: ACCENT, marginTop: 4, fontWeight: 700 }}>{fmtEUR(totalInvestment)}</div>
                <div style={{ ...mono, fontSize: 9, marginTop: 2, color: INK_SOFT }}>investissement</div>
              </div>
            </div>
            <div style={{ marginTop: 16, height: 18, display: 'flex', border: `1.4px solid ${INK}` }}>
              <div style={{ width: `${(landPrice / Math.max(totalInvestment, 1)) * 100}%`, background: INK_FAINT, borderRight: `1.2px solid ${INK}` }}></div>
              <div style={{ width: `${(constructionCost / Math.max(totalInvestment, 1)) * 100}%`, background: ACCENT }}></div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', ...mono, fontSize: 9, marginTop: 4 }}>
              <span>terrain · {((landPrice / Math.max(totalInvestment, 1)) * 100).toFixed(0)}%</span>
              <span>construction · {((constructionCost / Math.max(totalInvestment, 1)) * 100).toFixed(0)}%</span>
            </div>
          </Box>

          {/* ── Rent — explicit per-unit × count math ── */}
          <Box padding={20} label="ÉTAPE 3 · LOYERS PERÇUS">
            <div className="s-sim-kpi-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <div style={{ ...mono, fontSize: 10 }}>MENSUEL</div>
                <div style={{ fontFamily: "'Caveat', cursive", fontSize: 40, color: INK, marginTop: 2, fontWeight: 700, lineHeight: 1 }}>{fmtEUR(monthlyRent)}</div>
                <div style={{ ...mono, fontSize: 9, marginTop: 4, color: INK_SOFT }}>{numApts} × {fmtEUR(rentPerApt)} / mois</div>
              </div>
              <div>
                <div style={{ ...mono, fontSize: 10, color: ACCENT }}>ANNUEL</div>
                <div style={{ fontFamily: "'Caveat', cursive", fontSize: 40, color: ACCENT, marginTop: 2, fontWeight: 700, lineHeight: 1 }}>{fmtEUR(annualRent)}</div>
                <div style={{ ...mono, fontSize: 9, marginTop: 4, color: INK_SOFT }}>{fmtEUR(monthlyRent)} × 12 mois</div>
              </div>
            </div>
          </Box>

          {/* ── Headline KPIs — final answer ── */}
          <div className="s-sim-kpi-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Box padding={20} accent accentColor={ACCENT} style={{ borderColor: ACCENT, borderWidth: 2 }}>
              <div style={{ ...mono, fontSize: 10, color: ACCENT }}>ÉTAPE 4 · RENDEMENT BRUT</div>
              <div className="s-counter-grand" style={{ fontFamily: "'Caveat', cursive", fontSize: 96, lineHeight: .88, color: ACCENT, marginTop: 4, fontWeight: 700 }}>
                {grossYield.toFixed(1).replace('.', ',')}<span className="s-counter-pct" style={{ fontSize: 44 }}>&nbsp;%</span>
              </div>
              <div style={{ ...mono, fontSize: 9, marginTop: 8, color: INK_SOFT }}>{fmtEUR(annualRent)} ÷ {fmtEUR(totalInvestment)}</div>
            </Box>
            <Box padding={20} style={{ borderWidth: 2 }}>
              <div style={{ ...mono, fontSize: 10 }}>RETOUR SUR INVESTISSEMENT</div>
              <div className="s-counter-grand" style={{ fontFamily: "'Caveat', cursive", fontSize: 96, lineHeight: .88, color: INK, marginTop: 4, fontWeight: 700 }}>
                {isFinite(paybackYears) ? paybackYears.toFixed(1).replace('.', ',') : '∞'}<span className="s-counter-pct" style={{ fontSize: 44 }}>&nbsp;ans</span>
              </div>
              <div style={{ ...mono, fontSize: 9, marginTop: 8, color: INK_SOFT }}>{fmtEUR(totalInvestment)} ÷ {fmtEUR(annualRent)} / an</div>
            </Box>
          </div>
        </div>
      </div>

      <div style={{ marginTop: 22, ...mono, fontSize: 10, color: INK_SOFT, fontStyle: 'italic' }}>
        AVERTISSEMENT · rendement brut uniquement (hors taxes / charges / vacance) · hypothèse construction industrialisée · simulateur indicatif pour briefings investisseurs
      </div>
    </section>
  );
}

window.Simulator = Simulator;
