// Live landed-cost calculator section.

const { useState: useStateC, useMemo: useMemoC, useEffect: useEffectC } = React;

function Calculator({ t, lang, selectedId, setSelectedId }) {
  const car = useMemoC(() => CARS.find((c) => c.id === selectedId) || CARS[0], [selectedId]);
  const [animKey, setAnimKey] = useStateC(0);
  useEffectC(() => { setAnimKey((k) => k + 1); }, [selectedId]);

  const fee = Math.round(car.factory * car.feePct);
  const total = car.factory + car.freight + car.customs + fee;
  const save = car.dealer - total;
  const F = lang === "ar" ? fmtAr : fmt;
  const HINTS = {
    en: ["Guangzhou, ex-works", "Container · port to port", "Duties + plates + notary", "5% of factory price"],
    fr: ["Guangzhou, ex-works", "Conteneur · port à port", "Droits + plaques + notaire", "5% du prix usine"],
    es: ["Guangzhou, ex-works", "Contenedor · puerto a puerto", "Aranceles + placas + notario", "5% del precio de fábrica"],
    ar: ["غوانغجو، تسليم المصنع", "حاوية · مرفأ إلى مرفأ", "رسوم + لوحات + كاتب عدل", "٥٪ من سعر المصنع"],
  };
  const h = HINTS[lang] || HINTS.en;
  const lines = [
    { k: t.calc.lines.factory, v: car.factory, hint: h[0] },
    { k: t.calc.lines.freight, v: car.freight, hint: h[1] },
    { k: t.calc.lines.customs, v: car.customs, hint: h[2] },
    { k: t.calc.lines.fee, v: fee, hint: h[3] },
  ];

  return (
    <section id="cost" style={{ padding: "120px 0", borderTop: "1px solid var(--line)", background: "var(--ink-0)" }}>
      <div className="wrap">
        <SectionLabel eyebrow={t.calc.eyebrow} title={t.calc.title} sub={t.calc.sub} lang={lang} />

        {/* Car selector chips */}
        <div data-reveal style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 32 }}>
          {CARS.map((c) => {
            const active = c.id === selectedId;
            return (
              <button key={c.id} onClick={() => setSelectedId(c.id)}
                      style={{
                        background: active ? "var(--bone)" : "transparent",
                        color: active ? "var(--ink-0)" : "var(--bone)",
                        border: "1px solid " + (active ? "var(--bone)" : "var(--line-2)"),
                        borderRadius: 999, padding: "9px 16px", fontSize: 13, cursor: "pointer",
                        transition: "all .2s", fontFamily: "var(--sans)",
                      }}
                      onMouseEnter={(e) => { if (!active) e.currentTarget.style.borderColor = "var(--bone)"; }}
                      onMouseLeave={(e) => { if (!active) e.currentTarget.style.borderColor = "var(--line-2)"; }}>
                {c.name}
              </button>
            );
          })}
        </div>

        <div className="calc-card" style={{ borderRadius: 6, padding: "clamp(28px, 4vw, 48px)" }} data-reveal>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.1fr)", gap: "clamp(32px, 5vw, 72px)" }} className="calc-grid">
            {/* Visual side */}
            <div>
              <div style={{ aspectRatio: "16/10", border: "1px solid var(--line)", borderRadius: 4, overflow: "hidden", position: "relative", background: "linear-gradient(160deg, #1a1a1f 0%, #0a0a0b 100%)" }}>
                <CarSilhouette key={"viz-" + animKey} palette={car.palette} variant={car.type.en} />
              </div>
              <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16, flexWrap: "wrap" }}>
                <div>
                  <div className="serif" style={{ fontSize: "clamp(28px, 3.5vw, 40px)", color: "var(--bone)", letterSpacing: "-0.01em", lineHeight: 1 }}>
                    {car.name}
                  </div>
                  <div className="mono" style={{ marginTop: 6, fontSize: 11, color: "var(--mute-2)", letterSpacing: "0.12em", textTransform: "uppercase" }}>
                    {car.type[lang]}
                  </div>
                </div>
                {car.badge && (
                  <span className="mono" style={{ fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--amber)", border: "1px solid rgba(245,165,36,0.35)", borderRadius: 999, padding: "5px 10px" }}>
                    {car.badge}
                  </span>
                )}
              </div>
            </div>

            {/* Numbers side */}
            <div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--mute-2)", marginBottom: 16 }}>
                {t.misc?.breakdown || "Breakdown · USD"}
              </div>
              <div>
                {lines.map((l, i) => (
                  <div key={"l-" + animKey + "-" + i} className={i === 0 ? "" : "row-line"}
                       style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "16px 0", gap: 16, animation: "tick .35s ease both", animationDelay: (i * 0.05) + "s" }}>
                    <div>
                      <div style={{ fontSize: 14, color: "var(--bone)" }}>{l.k}</div>
                      <div style={{ fontSize: 11, color: "var(--mute-2)", marginTop: 3 }}>{l.hint}</div>
                    </div>
                    <div className="num" style={{ fontSize: 16, color: "var(--bone)", fontWeight: 500, fontVariantNumeric: "tabular-nums" }}>
                      {F(l.v)}
                    </div>
                  </div>
                ))}
                {/* Total */}
                <div key={"tot-" + animKey} className="row-line" style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "22px 0 12px", borderTopColor: "var(--line-2)", borderTopStyle: "solid", animation: "tick .4s ease both", animationDelay: "0.25s" }}>
                  <div className="serif" style={{ fontSize: 22, color: "var(--bone)", letterSpacing: "-0.005em" }}>
                    {t.calc.lines.total}
                  </div>
                  <div className="serif num" style={{ fontSize: 32, color: "var(--bone)", letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>
                    {F(total)}
                  </div>
                </div>

                {/* Comparison */}
                <div style={{ marginTop: 8, padding: "20px 20px", background: "rgba(109,190,126,0.06)", border: "1px solid rgba(109,190,126,0.18)", borderRadius: 4 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
                    <div style={{ fontSize: 13, color: "var(--mute)" }}>{t.calc.lines.dealer}</div>
                    <div className="num" style={{ fontSize: 14, color: "var(--mute)", textDecoration: "line-through", fontVariantNumeric: "tabular-nums" }}>
                      ~ {F(car.dealer)}
                    </div>
                  </div>
                  <div key={"sv-" + animKey} style={{ marginTop: 12, display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, animation: "tick .45s ease both", animationDelay: "0.35s" }}>
                    <div className="serif" style={{ fontSize: 22, color: "var(--green)", letterSpacing: "-0.005em", fontStyle: "italic" }}>
                      {t.calc.lines.save}
                    </div>
                    <div className="serif num" style={{ fontSize: 32, color: "var(--green)", letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums", fontWeight: 500 }}>
                      {F(save)}
                    </div>
                  </div>
                </div>

                <div style={{ marginTop: 24, display: "flex", flexWrap: "wrap", gap: 10 }}>
                  <a href={WA.beirut + "%20Model%3A%20" + encodeURIComponent(car.name)} target="_blank" rel="noopener" className="btn btn-wa" style={{ flex: 1, minWidth: 220 }}>
                    <WAIcon /> {t.misc?.exactQuote || "Get exact quote on WhatsApp"}
                  </a>
                </div>
                <div className="mono" style={{ marginTop: 16, fontSize: 10, letterSpacing: "0.08em", color: "var(--mute-2)", lineHeight: 1.6 }}>
                  {t.misc?.estimatesFoot || "Estimates based on May 2026 ex-works pricing."}
                </div>
              </div>
            </div>
          </div>

          <style>{`
            @media (max-width: 820px) {
              .calc-grid { grid-template-columns: 1fr !important; }
            }
          `}</style>
        </div>
      </div>
    </section>
  );
}

window.Calculator = Calculator;
