// demo.jsx — Live break-even calculator with reactive SVG chart

const fmtCOP = (n, lang) => {
  if (!isFinite(n)) return "—";
  const v = Math.round(n);
  return v.toLocaleString(lang === "en" ? "en-US" : "es-CO", { maximumFractionDigits: 0 });
};

function Slider({ label, value, onChange, min, max, step, suffix, accent }) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div style={{display:"flex", flexDirection:"column", gap:10}}>
      <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline"}}>
        <span className="mono" style={{fontSize:11, letterSpacing:".14em", textTransform:"uppercase", color:"var(--bone-3)"}}>{label}</span>
        <span className="mono tnum" style={{fontSize:14, color:"var(--bone)"}}>{value.toLocaleString()} <span style={{color:"var(--bone-3)", fontSize:11, marginLeft:4}}>{suffix}</span></span>
      </div>
      <div style={{position:"relative", height:24, display:"flex", alignItems:"center"}}>
        <div style={{position:"absolute", left:0, right:0, height:1, background:"var(--rule-2)"}}></div>
        <div style={{position:"absolute", left:0, width:`${pct}%`, height:1, background:"var(--accent)"}}></div>
        <div style={{position:"absolute", left:`calc(${pct}% - 6px)`, width:12, height:12, borderRadius:"50%", background:"var(--accent)", boxShadow:"0 0 0 4px rgba(10,9,8,1)"}}></div>
        <input type="range" min={min} max={max} step={step} value={value} onChange={(e)=>onChange(Number(e.target.value))}
          style={{position:"absolute", inset:0, width:"100%", opacity:0, cursor:"ew-resize", margin:0}}/>
      </div>
    </div>
  );
}

function StatCard({ label, value, sub, accent }) {
  return (
    <div style={{padding:"22px 24px", border:"1px solid var(--rule-2)", display:"flex", flexDirection:"column", gap:8, background:"rgba(244,240,232,.015)"}}>
      <div className="mono" style={{fontSize:10, letterSpacing:".18em", textTransform:"uppercase", color:"var(--bone-3)"}}>{label}</div>
      <div className="display-rom tnum" style={{fontSize:36, lineHeight:1, color: accent ? "var(--accent)" : "var(--bone)"}}>{value}</div>
      {sub && <div className="mono" style={{fontSize:11, color:"var(--bone-3)"}}>{sub}</div>}
    </div>
  );
}

function BreakEvenChart({ fixed, price, varCost, target, beUnits, targetUnits, lang }) {
  const W = 720, H = 320, PAD = 40;
  const maxX = Math.max(targetUnits * 1.4, beUnits * 1.6, 100);
  const maxY = Math.max(price * maxX, fixed + varCost * maxX, fixed * 2);

  const x = (u) => PAD + ((W - PAD - 16) * u) / maxX;
  const y = (v) => H - PAD - ((H - PAD - 16) * v) / maxY;

  // Lines
  const revenue = `M ${x(0)} ${y(0)} L ${x(maxX)} ${y(price * maxX)}`;
  const totalCost = `M ${x(0)} ${y(fixed)} L ${x(maxX)} ${y(fixed + varCost * maxX)}`;
  const fixedLine = `M ${x(0)} ${y(fixed)} L ${x(maxX)} ${y(fixed)}`;

  // Filled profit area between revenue and total cost (after BE)
  const profitArea = `M ${x(beUnits)} ${y(price * beUnits)} L ${x(maxX)} ${y(price * maxX)} L ${x(maxX)} ${y(fixed + varCost * maxX)} L ${x(beUnits)} ${y(fixed + varCost * beUnits)} Z`;

  // Grid lines
  const gridY = [];
  for (let i = 1; i < 5; i++) {
    gridY.push({y: H - PAD - ((H - PAD - 16) * i) / 5, v: maxY * i / 5});
  }

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{width:"100%", height:"auto", display:"block", overflow:"hidden"}}>
      <defs>
        <clipPath id="chartClip"><rect x={PAD} y={16} width={W - PAD - 16} height={H - PAD - 16}/></clipPath>
      </defs>
      <g clipPath="url(#chartClip)">
      {/* grid */}
      {gridY.map((g,i) => (
        <line key={i} x1={PAD} x2={W-16} y1={g.y} y2={g.y} stroke="var(--rule)" strokeWidth="1"/>
      ))}
      {/* axes */}
      <line x1={PAD} x2={W-16} y1={H-PAD} y2={H-PAD} stroke="var(--bone-3)" strokeWidth="1"/>
      <line x1={PAD} x2={PAD} y1={16} y2={H-PAD} stroke="var(--bone-3)" strokeWidth="1"/>

      {/* profit fill */}
      <path d={profitArea} fill="var(--accent)" opacity="0.14"/>

      {/* fixed cost line */}
      <path d={fixedLine} stroke="var(--bone-3)" strokeWidth="1" strokeDasharray="3 4" fill="none"/>
      {/* total cost */}
      <path d={totalCost} stroke="var(--bone-2)" strokeWidth="1.5" fill="none"/>
      {/* revenue */}
      <path d={revenue} stroke="var(--accent)" strokeWidth="2" fill="none"/>

      {/* BE marker */}
      {beUnits > 0 && beUnits < maxX && (
        <g>
          <line x1={x(beUnits)} x2={x(beUnits)} y1={y(price*beUnits)} y2={H-PAD} stroke="var(--accent)" strokeWidth="1" strokeDasharray="2 3"/>
          <circle cx={x(beUnits)} cy={y(price*beUnits)} r="5" fill="var(--accent)"/>
          <circle cx={x(beUnits)} cy={y(price*beUnits)} r="10" fill="none" stroke="var(--accent)" strokeWidth="1" opacity="0.4"/>
        </g>
      )}

      {/* target marker */}
      {targetUnits > 0 && targetUnits < maxX && (
        <g>
          <circle cx={x(targetUnits)} cy={y(price*targetUnits)} r="4" fill="var(--bone)"/>
        </g>
      )}

      </g>
      {/* labels (outside clip so they're never cut off) */}
      <text x={W-20} y={y(price*maxX)-8} textAnchor="end" fill="var(--accent)" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="1">
        {lang === "es" ? "INGRESOS" : "REVENUE"}
      </text>
      <text x={W-20} y={y(fixed+varCost*maxX)+14} textAnchor="end" fill="var(--bone-2)" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="1">
        {lang === "es" ? "COSTOS TOTALES" : "TOTAL COST"}
      </text>
      <text x={PAD+8} y={y(fixed)-6} fill="var(--bone-3)" fontFamily="IBM Plex Mono" fontSize="10" letterSpacing="1">
        {lang === "es" ? "COSTO FIJO" : "FIXED COST"}
      </text>
    </svg>
  );
}

function BreakEvenDemo({ copy, lang }) {
  const [fixed, setFixed] = React.useState(15000000);
  const [price, setPrice] = React.useState(80000);
  const [varCostRaw, setVarCost] = React.useState(35000);
  const [target, setTarget] = React.useState(8000000);
  // Always keep variable cost strictly below price (preserves a positive margin)
  const varCost = Math.min(varCostRaw, Math.max(price - 5000, 5000));

  const margin = price - varCost;
  const marginPct = price > 0 ? (margin / price) * 100 : 0;
  const beUnits = margin > 0 ? Math.ceil(fixed / margin) : Infinity;
  const targetUnits = margin > 0 ? Math.ceil((fixed + target) / margin) : Infinity;
  const revenueAtBe = isFinite(beUnits) ? beUnits * price : 0;

  return (
    <section id="demo" className="rule" style={{background:"linear-gradient(180deg, rgba(244,240,232,.025), transparent 60%)"}}>
      <SectionHead eyebrow={copy.demo.eyebrow} title={copy.demo.title} lede={copy.demo.lede} mode="italic"/>
      <div className="wrap">
        <div data-reveal style={{
          display:"grid", gridTemplateColumns:"380px 1fr", gap:48, alignItems:"start",
          border:"1px solid var(--rule-2)", padding:32, background:"rgba(0,0,0,.3)"
        }}>
          {/* Controls */}
          <div style={{display:"flex", flexDirection:"column", gap:28}}>
            <div className="mono" style={{display:"flex", justifyContent:"space-between", alignItems:"center", padding:"0 0 14px", borderBottom:"1px solid var(--rule)", fontSize:10, letterSpacing:".18em", textTransform:"uppercase", color:"var(--bone-3)"}}>
              <span>● {lang === "es" ? "INPUT" : "INPUT"}</span>
              <span style={{color:"var(--accent)"}}>// LIVE</span>
            </div>
            <Slider label={copy.demo.labels.fixed} value={fixed} onChange={setFixed} min={1000000} max={50000000} step={500000} suffix={copy.demo.labels.currency}/>
            <Slider label={copy.demo.labels.price} value={price} onChange={setPrice} min={10000} max={200000} step={5000} suffix={copy.demo.labels.currency}/>
            <Slider label={copy.demo.labels.varCost} value={Math.min(varCost, Math.max(price-5000, 5000))} onChange={(v)=>setVarCost(Math.min(v, Math.max(price-5000, 5000)))} min={5000} max={Math.max(price-5000, 5000)} step={2500} suffix={copy.demo.labels.currency}/>
            <Slider label={copy.demo.labels.target} value={target} onChange={setTarget} min={0} max={30000000} step={500000} suffix={copy.demo.labels.currency}/>
          </div>

          {/* Output */}
          <div style={{display:"flex", flexDirection:"column", gap:24}}>
            <BreakEvenChart fixed={fixed} price={price} varCost={varCost} target={target} beUnits={beUnits} targetUnits={targetUnits} lang={lang}/>

            <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:0, border:"1px solid var(--rule-2)"}}>
              <div style={{padding:"20px 22px", borderRight:"1px solid var(--rule)"}}>
                <div className="mono" style={{fontSize:10, letterSpacing:".18em", textTransform:"uppercase", color:"var(--bone-3)", marginBottom:6}}>{copy.demo.labels.margin}</div>
                <div className="display-rom tnum" style={{fontSize:24, color:"var(--bone)"}}>{fmtCOP(margin, lang)}</div>
                <div className="mono tnum" style={{fontSize:11, color:"var(--bone-3)", marginTop:4}}>{marginPct.toFixed(1)}% {copy.demo.labels.marginPct}</div>
              </div>
              <div style={{padding:"20px 22px", borderRight:"1px solid var(--rule)"}}>
                <div className="mono" style={{fontSize:10, letterSpacing:".18em", textTransform:"uppercase", color:"var(--bone-3)", marginBottom:6}}>{copy.demo.labels.be}</div>
                <div className="display-rom tnum" style={{fontSize:24, color:"var(--accent)"}}>{isFinite(beUnits) ? beUnits.toLocaleString() : "—"}</div>
                <div className="mono" style={{fontSize:11, color:"var(--bone-3)", marginTop:4}}>{copy.demo.labels.units}</div>
              </div>
              <div style={{padding:"20px 22px", borderRight:"1px solid var(--rule)"}}>
                <div className="mono" style={{fontSize:10, letterSpacing:".18em", textTransform:"uppercase", color:"var(--bone-3)", marginBottom:6}}>{copy.demo.labels.forTarget}</div>
                <div className="display-rom tnum" style={{fontSize:24, color:"var(--bone)"}}>{isFinite(targetUnits) ? targetUnits.toLocaleString() : "—"}</div>
                <div className="mono" style={{fontSize:11, color:"var(--bone-3)", marginTop:4}}>{copy.demo.labels.units}</div>
              </div>
              <div style={{padding:"20px 22px"}}>
                <div className="mono" style={{fontSize:10, letterSpacing:".18em", textTransform:"uppercase", color:"var(--bone-3)", marginBottom:6}}>{copy.demo.labels.revenueAtBe}</div>
                <div className="display-rom tnum" style={{fontSize:24, color:"var(--bone)"}}>{fmtCOP(revenueAtBe, lang)}</div>
                <div className="mono" style={{fontSize:11, color:"var(--bone-3)", marginTop:4}}>{copy.demo.labels.currency}</div>
              </div>
            </div>

            <div className="mono" style={{fontSize:10, letterSpacing:".14em", color:"var(--bone-3)", textAlign:"right"}}>{copy.demo.labels.note}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.BreakEvenDemo = BreakEvenDemo;
