/* LandedCost — true cost to land 1 unit at FBA + ROI verdict.
 * Different lens from ProfitCalcPro: upstream-focused, designed for
 * "should we buy this case?" decisions during sourcing.
 */

const LandedCost = () => {
  const [v, setV] = useState({ ...window.LANDED_DEFAULTS });
  const set = (k) => (val) => setV((s) => ({ ...s, [k]: val }));
  const r = window.calcLandedCost(v);

  const tone = r.verdict === "buy" ? "green" : r.verdict === "marginal" ? "amber" : "red";
  const toneVar = `var(--${tone})`;
  const verdictLabel = r.verdict === "buy" ? "Achat recommandé" : r.verdict === "marginal" ? "Marginal · surveiller" : "Passer";

  const breakdown = [
    { label: "Coût fournisseur",       value: r.unitCostCAD,    sub: `${v.currency} ${v.unitCost.toFixed(2)}${v.currency === "USD" ? ` × ${v.fx}` : ""}` },
    { label: "Transport entrant",      value: r.inboundUnit,    sub: `${fmtDollar(v.inboundTotal)} ÷ ${v.qty} u` },
    { label: "Douanes",                value: r.dutyUnit,       sub: `${v.dutyPct}% du coût` },
    { label: "Prep KCC",               value: r.prepPerUnit,    sub: "tarif standard" },
    { label: "Inspection",             value: r.inspecUnit,     sub: `${fmtDollar(v.inspectionFlat)} ÷ ${v.qty} u` },
    { label: "Casse / pertes",         value: r.damageBuffer,   sub: `${v.damagePct}% du coût` },
  ];

  const downstream = [
    { label: "Prix de vente",          value: v.sellPrice,      tone: "in"  },
    { label: "Landed cost",            value: -r.landedPerUnit, tone: "out" },
    { label: "Referral Amazon",        value: -r.referralFee,   tone: "out", sub: `${v.referralPct}%` },
    { label: "FBA fee",                value: -r.fbaFee,        tone: "out" },
    { label: "Stockage",               value: -r.storagePerUnit,tone: "out" },
    { label: "Retours",                value: -r.returnsCost,   tone: "out", sub: `${v.returnPct}%` },
  ];

  return (
    <div className="page" style={{ maxWidth: 1500 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Landed Cost</div>
          <div className="page-sub">Coût réel à l'entrepôt FBA · décision sourcing en un coup d'œil</div>
        </div>
        <div className="row">
          <button className="btn" data-variant="ghost" onClick={() => setV({ ...window.LANDED_DEFAULTS })}>
            <Icon name="refresh" size={13} /> Réinitialiser
          </button>
          <button className="btn"><Icon name="copy" size={13} /> Dupliquer</button>
          <button className="btn" data-variant="primary"><Icon name="check" size={13} /> Enregistrer scénario</button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr 380px", gap: 14, alignItems: "flex-start" }}>
        {/* Col 1 — upstream inputs */}
        <div className="card">
          <div className="card-head"><div className="card-title">Achat & logistique entrante</div></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="row" style={{ gap: 8 }}>
              <button
                className="btn"
                data-variant={v.currency === "CAD" ? "primary" : "ghost"}
                onClick={() => set("currency")("CAD")}
                style={{ flex: 1 }}
              >CAD</button>
              <button
                className="btn"
                data-variant={v.currency === "USD" ? "primary" : "ghost"}
                onClick={() => set("currency")("USD")}
                style={{ flex: 1 }}
              >USD</button>
            </div>
            <Slider label={`Coût unitaire (${v.currency})`} value={v.unitCost} onChange={set("unitCost")} min={0.1} max={200} step={0.05} format={fmtDollar} help="Prix négocié avec le fournisseur"/>
            {v.currency === "USD" && (
              <Slider label="Taux USD → CAD" value={v.fx} onChange={set("fx")} min={1.0} max={1.6} step={0.01} format={(x)=>x.toFixed(2)} help="Taux du jour ou couvert"/>
            )}
            <Slider label="Quantité commandée" value={v.qty} onChange={set("qty")} min={1} max={5000} step={1} format={(x)=>x.toString()} suffix=" u" help="Taille du lot acheté"/>
            <Slider label="Transport entrant (total CAD)" value={v.inboundTotal} onChange={set("inboundTotal")} min={0} max={5000} step={5} format={fmtDollar} help="Freight + dédouanement + dernier km"/>
            <Slider label="Douanes" value={v.dutyPct} onChange={set("dutyPct")} min={0} max={25} step={0.5} format={(x)=>x.toFixed(1)} suffix=" %" help="HS code dependent · 0% si origine ACEUM"/>
            <Slider label="Frais inspection (flat CAD)" value={v.inspectionFlat} onChange={set("inspectionFlat")} min={0} max={500} step={5} format={fmtDollar} help="QC tiers en usine si applicable"/>
            <Slider label="Casse estimée" value={v.damagePct} onChange={set("damagePct")} min={0} max={10} step={0.5} format={(x)=>x.toFixed(1)} suffix=" %" help="Pertes en transit (typique 1-3%)"/>
            <Slider label="Prep KCC" value={v.prepPerUnit} onChange={set("prepPerUnit")} min={0} max={3} step={0.05} format={fmtDollar} help="Étiquetage, bundling, polybag"/>
          </div>
        </div>

        {/* Col 2 — downstream sale */}
        <div className="card">
          <div className="card-head"><div className="card-title">Vente & frais Amazon</div></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Slider label="Prix de vente Amazon" value={v.sellPrice} onChange={set("sellPrice")} min={1} max={300} step={0.5} format={fmtDollar} help="Listing CA, taxes incluses"/>
            <Slider label="Referral Amazon" value={v.referralPct} onChange={set("referralPct")} 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.fbaFee} onChange={set("fbaFee")} min={2} max={20} step={0.1} format={fmtDollar} help="Tier petit standard CA : ~$3.50-$6"/>
            <Slider label="Stockage / unité / mois" value={v.storagePerUnit} onChange={set("storagePerUnit")} min={0} max={5} step={0.05} format={fmtDollar} help="Variable selon Q4 / hors-Q4"/>
            <Slider label="Taux retours" value={v.returnPct} onChange={set("returnPct")} min={0} max={15} step={0.1} format={(x)=>x.toFixed(1)} suffix=" %" help="Retours + remboursements"/>
          </div>

          {/* Upstream breakdown */}
          <div className="card-head" style={{ marginTop: 4, borderTop: "1px solid var(--border-subtle)" }}>
            <div className="card-title">Décomposition landed cost</div>
            <span className="num" style={{ fontSize: 12.5, fontWeight: 600 }}>{fmtDollar(r.landedPerUnit)} / u</span>
          </div>
          <div>
            {breakdown.map((row) => (
              <div key={row.label} className="row" style={{ padding: "8px 14px", borderBottom: "1px solid var(--border-subtle)", justifyContent: "space-between" }}>
                <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
                  <span style={{ fontSize: 11.5 }}>{row.label}</span>
                  <span style={{ fontSize: 10, color: "var(--text-faint)" }}>{row.sub}</span>
                </div>
                <span className="num" style={{ fontSize: 12.5, fontWeight: 500 }}>{fmtDollar(row.value)}</span>
              </div>
            ))}
            <div className="row" style={{ padding: "10px 14px", justifyContent: "space-between", background: "var(--bg-1)" }}>
              <span style={{ fontSize: 11.5, fontWeight: 600 }}>Total landed / unité</span>
              <span className="num" style={{ fontSize: 14, fontWeight: 700 }}>{fmtDollar(r.landedPerUnit)}</span>
            </div>
          </div>
        </div>

        {/* Right rail */}
        <div className="stack" style={{ gap: 14 }}>
          {/* Verdict card */}
          <div style={{
            position: "relative",
            border: `1px solid ${toneVar}`,
            borderRadius: 14,
            padding: "18px 18px 16px",
            overflow: "hidden",
            background: "var(--bg-1)",
            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 }}>Verdict sourcing</span>
              <Badge tone={tone}>{verdictLabel}</Badge>
            </div>
            <div style={{ position: "relative", marginTop: 8 }}>
              <div className="num" style={{ fontSize: 38, fontWeight: 600, color: toneVar, letterSpacing: "-0.03em", lineHeight: 1 }}>
                {r.profitUnit < 0 ? "−" : ""}{fmtDollar(Math.abs(r.profitUnit))}
              </div>
              <div className="row" style={{ gap: 6, marginTop: 4 }}>
                <span style={{ fontSize: 11.5, color: "var(--text-dim)" }}>profit / unité</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" }}>ROI</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600, color: toneVar }}>{r.roiPct.toFixed(1)}%</div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Marge</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600 }}>{r.marginPct.toFixed(1)}%</div>
              </div>
            </div>
          </div>

          {/* Totals card */}
          <div className="card">
            <div className="card-head"><div className="card-title">Totaux du lot</div></div>
            <div>
              <div className="row" style={{ padding: "9px 14px", borderBottom: "1px solid var(--border-subtle)", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11.5 }}>Marchandise</span>
                <span className="num" style={{ fontSize: 12.5 }}>{fmtDollar(r.goodsCAD)}</span>
              </div>
              <div className="row" style={{ padding: "9px 14px", borderBottom: "1px solid var(--border-subtle)", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11.5 }}>Transport entrant</span>
                <span className="num" style={{ fontSize: 12.5 }}>{fmtDollar(v.inboundTotal)}</span>
              </div>
              <div className="row" style={{ padding: "9px 14px", borderBottom: "1px solid var(--border-subtle)", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11.5 }}>Douanes</span>
                <span className="num" style={{ fontSize: 12.5 }}>{fmtDollar(r.dutyCAD)}</span>
              </div>
              <div className="row" style={{ padding: "10px 14px", justifyContent: "space-between", background: "var(--bg-1)" }}>
                <span style={{ fontSize: 11.5, fontWeight: 600 }}>Capital total à mobiliser</span>
                <span className="num" style={{ fontSize: 14, fontWeight: 700 }}>{fmtDollar(r.landedTotal)}</span>
              </div>
              <div className="row" style={{ padding: "10px 14px", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11.5, fontWeight: 600 }}>Profit total estimé</span>
                <span className="num" style={{ fontSize: 14, fontWeight: 700, color: toneVar }}>
                  {r.profitTotal < 0 ? "−" : ""}{fmtDollar(Math.abs(r.profitTotal))}
                </span>
              </div>
            </div>
          </div>

          {/* Break-even card */}
          <div className="card">
            <div className="card-head"><div className="card-title">Seuil de rentabilité</div></div>
            <div style={{ padding: 14 }}>
              <div style={{ fontSize: 11, color: "var(--text-dim)" }}>Prix de vente minimum pour ne pas perdre d'argent</div>
              <div className="num" style={{ fontSize: 22, fontWeight: 700, marginTop: 4 }}>{fmtDollar(r.breakEven)}</div>
              <div className="muted" style={{ fontSize: 10.5, marginTop: 6 }}>
                Cible saine: <span className="mono">≥ {fmtDollar(r.breakEven * 1.4)}</span> (40% au-dessus du break-even)
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.LandedCost = LandedCost;
