/* ProfitCalcPro — 10 sliders, live decomposition */

const DEFAULTS = {
  price: 49.99,
  cost: 12.40,
  referral: 15,    // %
  fba: 5.20,       // $ FBA fee
  ppc: 4.50,       // $ PPC
  returns: 3.5,    // %
  storage: 0.85,   // $/unit/month
  shipping: 2.10,  // $ inbound shipping per unit
  tva: 5,          // % (TPS Canada)
  volume: 320,     // units/month
};

const Decomp = ({ label, value, sub, tone = "default", percent }) => {
  const color = tone === "in" ? "var(--green)" : tone === "out" ? "var(--red)" : tone === "muted" ? "var(--text-muted)" : "var(--text)";
  const sign = tone === "out" ? "−" : tone === "in" ? "+" : "";
  return (
    <div className="row" style={{ padding: "9px 14px", borderBottom: "1px solid var(--border-subtle)", justifyContent: "space-between" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 1, minWidth: 0 }}>
        <span style={{ fontSize: 12, color: "var(--text)" }}>{label}</span>
        {sub && <span style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{sub}</span>}
      </div>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 1 }}>
        <span className="num" style={{ fontSize: 13.5, fontWeight: 600, color }}>{sign}{fmtDollar(Math.abs(value))}</span>
        {percent != null && <span className="mono" style={{ fontSize: 10, color: "var(--text-faint)" }}>{percent.toFixed(1)}%</span>}
      </div>
    </div>
  );
};

const ProfitCalcPro = () => {
  const [v, setV] = useState(DEFAULTS);
  const set = (k) => (val) => setV((s) => ({ ...s, [k]: val }));

  const referralFee = v.price * (v.referral / 100);
  const returnsCost = v.price * (v.returns / 100);
  const tvaCost     = v.price * (v.tva / 100);
  const totalIn     = v.price;
  const totalOut    = v.cost + referralFee + v.fba + v.ppc + returnsCost + v.storage + v.shipping + tvaCost;
  const profitUnit  = totalIn - totalOut;
  const marginPct   = (profitUnit / v.price) * 100;
  const profitMonth = profitUnit * v.volume;
  const revenueMonth= v.price * v.volume;

  const tone = marginPct >= 28 ? "green" : marginPct >= 20 ? "amber" : "red";
  const toneVar = `var(--${tone})`;

  return (
    <div className="page" style={{ maxWidth: 1500 }}>
      <div className="page-head">
        <div>
          <div className="page-title">ProfitCalcPro</div>
          <div className="page-sub">Décomposition $-par-unité · ajustez les 10 leviers pour voir la marge nette en temps réel</div>
        </div>
        <div className="row">
          <button className="btn" data-variant="ghost" onClick={() => setV(DEFAULTS)}><Icon name="refresh" size={13} /> Réinitialiser</button>
          <button className="btn"><Icon name="copy" size={13} /> Dupliquer scénario</button>
          <button className="btn" data-variant="primary"><Icon name="check" size={13} /> Enregistrer</button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr 380px", gap: 14, alignItems: "flex-start" }}>
        {/* Sliders col 1 */}
        <div className="card">
          <div className="card-head"><div className="card-title">Revenus & coût produit</div></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Slider label="Prix de vente"   value={v.price}    onChange={set("price")}    min={5}  max={200} step={0.5} format={fmtDollar} help="Prix listing Amazon CA, taxes incluses"/>
            <Slider label="Coût d'achat"    value={v.cost}     onChange={set("cost")}     min={1}  max={100} step={0.1} format={fmtDollar} help="Prix unitaire fournisseur, T/T converti CAD"/>
            <Slider label="Volume mensuel"  value={v.volume}   onChange={set("volume")}   min={10} max={2000} step={10} format={(x)=>x.toString()} suffix=" u" help="Unités vendues par mois (moyenne 90j)"/>
            <Slider label="Frais expédition entrant" value={v.shipping} onChange={set("shipping")} min={0} max={15} step={0.05} format={fmtDollar} help="Coût d'expédition fournisseur → entrepôt FBA"/>
          </div>
        </div>

        {/* Sliders col 2 */}
        <div className="card">
          <div className="card-head"><div className="card-title">Frais Amazon & opérations</div></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Slider label="Referral fee Amazon"    value={v.referral} onChange={set("referral")} min={6}    max={20}  step={0.5} format={(x)=>x.toFixed(1)} suffix=" %" help="Typiquement 8–15% selon catégorie"/>
            <Slider label="Frais FBA (pick & pack)" value={v.fba}      onChange={set("fba")}      min={2}    max={20}  step={0.1} format={fmtDollar} help="Tier petit standard CA : ~$3.50–$6"/>
            <Slider label="PPC (publicité)"         value={v.ppc}      onChange={set("ppc")}      min={0}    max={20}  step={0.1} format={fmtDollar} help="Coût publicitaire moyen par unité vendue"/>
            <Slider label="Retours (taux)"          value={v.returns}  onChange={set("returns")}  min={0}    max={15}  step={0.1} format={(x)=>x.toFixed(1)} suffix=" %" help="Pourcentage retours/remboursements"/>
            <Slider label="Stockage FBA"            value={v.storage}  onChange={set("storage")}  min={0}    max={5}   step={0.05} format={fmtDollar} help="Coût stockage par unité par mois"/>
            <Slider label="TPS/TVQ effective"       value={v.tva}      onChange={set("tva")}      min={0}    max={15}  step={0.5} format={(x)=>x.toFixed(1)} suffix=" %" help="Portion taxes non récupérable"/>
          </div>
        </div>

        {/* Right rail — decomposition + profit card */}
        <div className="stack" style={{ gap: 14 }}>
          {/* Profit card */}
          <div style={{
            position: "relative",
            background: `linear-gradient(140deg, ${toneVar.replace("var(--","oklch(0.3 0.05 ").replace(")","").replace("green","var(--green)").replace("amber","var(--amber)").replace("red","var(--red)")}, var(--bg-1) 70%)`,
            border: `1px solid ${toneVar}`,
            borderRadius: 14,
            padding: "18px 18px 16px",
            overflow: "hidden",
            boxShadow: `0 0 0 4px ${toneVar.replace(")", " / 0.08)")}`
          }}>
            <div style={{ position: "absolute", inset: 0, background: `radial-gradient(60% 80% at 100% 0%, ${toneVar.replace(")", " / 0.18)")}, transparent 70%)`, pointerEvents: "none" }}/>
            <div className="between" style={{ position: "relative" }}>
              <span style={{ fontSize: 11, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 500 }}>Profit unitaire</span>
              <Badge tone={tone}>
                {marginPct >= 28 ? "Marge OK" : marginPct >= 20 ? "Surveillance" : "Critique"}
              </Badge>
            </div>
            <div style={{ position: "relative", marginTop: 8 }}>
              <div className="num" style={{ fontSize: 38, fontWeight: 600, color: toneVar, letterSpacing: "-0.03em", lineHeight: 1 }}>
                {profitUnit < 0 ? "−" : ""}{fmtDollar(Math.abs(profitUnit))}
              </div>
              <div className="row" style={{ gap: 6, marginTop: 4 }}>
                <span className="num" style={{ fontSize: 16, fontWeight: 600 }}>{marginPct.toFixed(1)}%</span>
                <span style={{ fontSize: 11.5, color: "var(--text-dim)" }}>marge nette</span>
              </div>
            </div>
            <div className="divider" style={{ position: "relative" }}/>
            <div className="grid" style={{ position: "relative", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div>
                <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Revenu / mois</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600 }}>{fmtDollar(revenueMonth)}</div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Profit / mois</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600, color: toneVar }}>{profitUnit < 0 ? "−" : ""}{fmtDollar(Math.abs(profitMonth))}</div>
              </div>
            </div>
          </div>

          {/* Decomposition */}
          <div className="card">
            <div className="card-head">
              <div className="card-title">Décomposition $-par-unité</div>
              <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginLeft: "auto" }}>Volume {v.volume}/mois</span>
            </div>
            <div>
              <Decomp label="Prix de vente"           value={totalIn}   tone="in" />
              <Decomp label="Coût d'achat"           value={v.cost}      sub={`Fournisseur · ${(v.cost/v.price*100).toFixed(1)}% du prix`} tone="out" percent={v.cost/v.price*100} />
              <Decomp label="Referral Amazon"        value={referralFee} sub={`${v.referral}% du prix`}                                   tone="out" percent={referralFee/v.price*100} />
              <Decomp label="FBA pick & pack"        value={v.fba}                                                                          tone="out" percent={v.fba/v.price*100} />
              <Decomp label="PPC publicité"          value={v.ppc}       sub={`ACOS estimé ${(v.ppc/v.price*100).toFixed(1)}%`}            tone="out" percent={v.ppc/v.price*100} />
              <Decomp label="Retours"                value={returnsCost} sub={`Taux ${v.returns}%`}                                        tone="out" percent={returnsCost/v.price*100} />
              <Decomp label="Stockage FBA"           value={v.storage}                                                                      tone="out" percent={v.storage/v.price*100} />
              <Decomp label="Expédition entrante"    value={v.shipping}                                                                     tone="out" percent={v.shipping/v.price*100} />
              <Decomp label="TPS/TVQ effective"      value={tvaCost}     sub={`${v.tva}% non-récupérable`}                                 tone="out" percent={tvaCost/v.price*100} />
              <div className="row" style={{ padding: "10px 14px", background: "var(--bg-2)", justifyContent: "space-between" }}>
                <span style={{ fontSize: 12, fontWeight: 600 }}>Profit net unitaire</span>
                <span className="num" style={{ fontSize: 14, fontWeight: 600, color: toneVar }}>{profitUnit < 0 ? "−" : ""}{fmtDollar(Math.abs(profitUnit))}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ProfitCalcPro = ProfitCalcPro;
