/* global React, Icon, Button, Badge, useState, useEffect, useRef */

/* Recomendador de baldes: cubre los litros con el menor sobrante razonable */
function recommendCans(liters, presList) {
  const sizes = [...presList].sort((a, b) => b.liters - a.liters);
  let rem = liters;
  const picks = [];
  for (const s of sizes) {
    const n = Math.floor(rem / s.liters + 1e-9);
    if (n > 0) { picks.push({ pres: s, count: n }); rem -= n * s.liters; }
  }
  if (rem > 0.01) {
    const cover = [...presList].filter((s) => s.liters >= rem - 1e-9).sort((a, b) => a.liters - b.liters)[0] || sizes[sizes.length - 1];
    const ex = picks.find((p) => p.pres.id === cover.id);
    if (ex) ex.count++; else picks.push({ pres: cover, count: 1 });
    rem -= cover.liters;
  }
  const totalLiters = picks.reduce((s, p) => s + p.pres.liters * p.count, 0);
  return { picks, totalLiters };
}

const ENVIRONMENTS = [
  { id: "interior", label: "Pared interior", coatHint: 2 },
  { id: "cocina", label: "Cocina / Baño", coatHint: 2 },
  { id: "exterior", label: "Frente / Exterior", coatHint: 2 },
  { id: "techo", label: "Techo / Terraza", coatHint: 3 },
  { id: "madera", label: "Madera / Metal", coatHint: 2 },
];

function Typing() {
  return <div className="bubble bubble--bot"><span className="typing"><span /><span /><span /></span></div>;
}

function BotFlow({ product, presId, color, onConfirm, onClose }) {
  const NOGO = window.NOGO;
  const [msgs, setMsgs] = useState([]);
  const [step, setStep] = useState("intro");      // intro|ctx|area|dims|coats|result
  const [typing, setTyping] = useState(false);
  const [ctx, setCtx] = useState(null);
  const [area, setArea] = useState("");
  const [coats, setCoats] = useState(product.manos);
  const [dims, setDims] = useState({ peri: "", alto: "" });
  const [extras, setExtras] = useState([]);
  const feedRef = useRef(null);

  const push = (m) => setMsgs((prev) => [...prev, { id: Date.now() + Math.random(), ...m }]);

  // auto-scroll
  useEffect(() => {
    if (feedRef.current) feedRef.current.scrollTop = feedRef.current.scrollHeight;
  }, [msgs, typing, step]);

  // mensaje del bot con "typing" previo
  const botSay = (content, delay = 650) => {
    setTyping(true);
    return new Promise((res) => setTimeout(() => {
      setTyping(false);
      push({ from: "bot", content });
      res();
    }, delay));
  };

  // arranque
  useEffect(() => {
    let alive = true;
    (async () => {
      await botSay(<>¡Hola! Soy <b>Nilo</b>, tu asesor de pintura 🎨 Sumaste <b>{product.name}</b>. En 3 pasos calculo cuánta pintura necesitás para no comprar de más ni de menos.</>, 500);
      if (!alive) return;
      await botSay(<>¿Dónde vas a pintar?</>, 700);
      if (alive) setStep("ctx");
    })();
    return () => { alive = false; };
  }, []);

  const chooseEnv = async (env) => {
    push({ from: "user", content: env.label });
    setCtx(env); setCoats(env.coatHint);
    setStep("intro");
    await botSay(<>Perfecto. ¿Cuántos <b>m²</b> vas a pintar? Si no sabés, te ayudo a calcularlo con las medidas.</>, 700);
    setStep("area");
  };

  const submitArea = async (m2) => {
    push({ from: "user", content: `${m2} m²` });
    setStep("intro");
    await botSay(<>Genial. Para esta superficie suelo recomendar <b>{ctx.coatHint} manos</b>. ¿Confirmás o ajustás?</>, 650);
    setStep("coats");
  };

  const computeFromDims = () => {
    const peri = parseFloat(dims.peri), alto = parseFloat(dims.alto);
    if (!peri || !alto) return;
    const m2 = Math.round(peri * alto);
    setArea(String(m2));
    submitArea(m2);
  };

  const confirmCoats = async (c) => {
    setCoats(c);
    push({ from: "user", content: `${c} ${c === 1 ? "mano" : "manos"}` });
    setStep("intro");
    const m2 = parseFloat(area);
    const litersNeeded = (m2 * c) / product.rendimiento;
    const rec = recommendCans(litersNeeded, NOGO.presentations.filter((p) => product.pres.includes(p.id)));
    await botSay(<>Listo, hice el cálculo 👇</>, 800);
    push({ from: "bot", kind: "calc", litersNeeded, rec, m2, coats: c });
    await botSay(<>Para que el trabajo quede impecable, sumá estos complementos. ¿Te agrego alguno?</>, 900);
    setStep("result");
    // guardo recomendación para el confirm
    window.__lastRec = rec;
  };

  const toggleExtra = (id) =>
    setExtras((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]);

  const finish = () => {
    const rec = window.__lastRec;
    const items = rec.picks.map((p) => ({
      productId: product.id, name: product.name, presId: p.pres.id,
      presLabel: `${p.pres.label} ${p.pres.unit}`, qty: p.count,
      price: NOGO.priceFor(product, p.pres.id), color,
    }));
    const accItems = extras.map((id) => {
      const a = NOGO.accessories.find((x) => x.id === id);
      return { productId: a.id, name: a.name, presId: "u", presLabel: "Unidad", qty: 1, price: a.price, color: null };
    });
    onConfirm([...items, ...accItems]);
  };

  const recoExtras = ["rodillo", "cinta", ctx && ctx.id === "interior" ? "enduido" : "lija"].filter(Boolean);

  return (
    <div className="bot">
      <div className="bot__head">
        <div className="bot__avatar"><Icon name="drop" size={20} /></div>
        <div style={{ flex: 1 }}>
          <div className="bot__name">Nilo · Asesor Nogopaint</div>
          <div className="bot__status">Calculando con datos reales del producto</div>
        </div>
        <button className="btn--icon" style={{ width: 40, height: 40, display: "grid", placeItems: "center", borderRadius: 999 }} onClick={onClose} aria-label="Cerrar"><Icon name="x" /></button>
      </div>

      <div className="bot__feed" ref={feedRef}>
        {msgs.map((m) => {
          if (m.kind === "calc") return <CalcCard key={m.id} {...m} product={product} />;
          return <div key={m.id} className={`bubble bubble--${m.from}`}>{m.content}</div>;
        })}
        {typing && <Typing />}

        {/* zona interactiva inline segun step */}
        {!typing && step === "ctx" && (
          <div className="bot__quick">
            {ENVIRONMENTS.map((e) => (
              <button key={e.id} className="quick" onClick={() => chooseEnv(e)}>{e.label}</button>
            ))}
          </div>
        )}

        {!typing && step === "coats" && (
          <div className="bot__quick">
            {[1, 2, 3].map((c) => (
              <button key={c} className="quick" onClick={() => confirmCoats(c)}>
                {c} {c === 1 ? "mano" : "manos"}{c === ctx?.coatHint ? " (recomendado)" : ""}
              </button>
            ))}
          </div>
        )}

        {!typing && step === "result" && (
          <div className="col gap-2" style={{ alignSelf: "stretch" }}>
            {recoExtras.map((id) => {
              const a = NOGO.accessories.find((x) => x.id === id);
              const on = extras.includes(id);
              return (
                <button key={id} className="card" onClick={() => toggleExtra(id)}
                  style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, textAlign: "left", borderColor: on ? "var(--accent)" : "var(--border-subtle)", background: on ? "var(--accent-soft)" : "var(--bg-surface)", cursor: "pointer" }}>
                  <span style={{ width: 36, height: 36, borderRadius: 8, background: "var(--bg-surface-alt)", display: "grid", placeItems: "center", flex: "none" }}><Icon name="brush" size={18} /></span>
                  <span style={{ flex: 1 }}>
                    <span className="fw-6 strong t-sm" style={{ display: "block" }}>{a.name}</span>
                    <span className="t-xs muted">{NOGO.fmt(a.price)}</span>
                  </span>
                  <span style={{ width: 24, height: 24, borderRadius: 6, border: "1.5px solid", borderColor: on ? "var(--accent)" : "var(--border-strong)", background: on ? "var(--accent)" : "transparent", display: "grid", placeItems: "center", color: "#fff", flex: "none" }}>
                    {on && <Icon name="check" size={14} stroke={3} />}
                  </span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* footer: input de m² o CTA final */}
      {step === "area" && (
        <AreaInput dims={dims} setDims={setDims} area={area} setArea={setArea} onSubmit={submitArea} onCalc={computeFromDims} />
      )}
      {step === "result" && (
        <div className="bot__input" style={{ display: "block", padding: "var(--space-3) var(--space-4)" }}>
          <Button block variant="cta" icon="cart" onClick={finish}>Agregar todo al carrito</Button>
        </div>
      )}
    </div>
  );
}

/* Input de m² con calculadora por medidas */
function AreaInput({ dims, setDims, area, setArea, onSubmit, onCalc }) {
  const [mode, setMode] = useState("direct"); // direct | calc
  return (
    <div className="bot__input" style={{ display: "block", padding: "var(--space-3) var(--space-4)" }}>
      <div className="segmented" style={{ marginBottom: 10 }}>
        <button className={`pill ${mode === "direct" ? "pill--active" : ""}`} style={{ flex: 1, minWidth: 0 }} onClick={() => setMode("direct")}><span>Sé los m²</span></button>
        <button className={`pill ${mode === "calc" ? "pill--active" : ""}`} style={{ flex: 1, minWidth: 0 }} onClick={() => setMode("calc")}><span>Calcular por medidas</span></button>
      </div>
      {mode === "direct" ? (
        <div className="row gap-2">
          <input className="input" type="number" inputMode="decimal" placeholder="Ej: 45" value={area} onChange={(e) => setArea(e.target.value)} />
          <span className="muted fw-6" style={{ alignSelf: "center" }}>m²</span>
          <Button icon="send" disabled={!area || +area <= 0} onClick={() => onSubmit(area)}>Calcular</Button>
        </div>
      ) : (
        <div className="col gap-2">
          <div className="row gap-2">
            <input className="input" type="number" inputMode="decimal" placeholder="Perímetro (m)" value={dims.peri} onChange={(e) => setDims({ ...dims, peri: e.target.value })} />
            <input className="input" type="number" inputMode="decimal" placeholder="Alto (m)" value={dims.alto} onChange={(e) => setDims({ ...dims, alto: e.target.value })} />
          </div>
          <Button block disabled={!dims.peri || !dims.alto} onClick={onCalc}>Calcular superficie</Button>
        </div>
      )}
    </div>
  );
}

/* Tarjeta de resultado del cálculo */
function CalcCard({ litersNeeded, rec, m2, coats, product }) {
  const NOGO = window.NOGO;
  const totalPrice = rec.picks.reduce((s, p) => s + NOGO.priceFor(product, p.pres.id) * p.count, 0);
  const leftover = (rec.totalLiters - litersNeeded);
  return (
    <div className="calc-card">
      <div className="t-xs" style={{ opacity: .8, textTransform: "uppercase", letterSpacing: ".06em", fontWeight: 700 }}>Necesitás aproximadamente</div>
      <div className="calc-card__row" style={{ margin: "4px 0 12px" }}>
        <span className="calc-card__big">{litersNeeded.toFixed(1)}</span>
        <span className="t-lg fw-6">litros</span>
        <span className="t-xs" style={{ opacity: .75, marginLeft: "auto", alignSelf: "flex-end" }}>{m2} m² · {coats} {coats === 1 ? "mano" : "manos"}</span>
      </div>
      <div style={{ background: "rgba(255,255,255,0.1)", borderRadius: 10, padding: "10px 14px", marginBottom: 12 }}>
        <div className="t-xs fw-6" style={{ opacity: .85, marginBottom: 4 }}>Te recomendamos comprar</div>
        {rec.picks.map((p) => (
          <div key={p.pres.id} className="calc-line">
            <span>{p.count} × balde de {p.pres.label} {p.pres.unit}</span>
            <span className="fw-7">{NOGO.fmt(NOGO.priceFor(product, p.pres.id) * p.count)}</span>
          </div>
        ))}
      </div>
      <div className="row between t-sm">
        <span style={{ opacity: .85 }}>Total pintura · {rec.totalLiters} L</span>
        <span className="disp fw-7 t-lg">{NOGO.fmt(totalPrice)}</span>
      </div>
      {leftover > 0.05 && (
        <div className="t-xs" style={{ opacity: .7, marginTop: 6 }}>Te sobra ~{leftover.toFixed(1)} L para retoques. Rinde {product.rendimiento} m²/L por mano.</div>
      )}
    </div>
  );
}

Object.assign(window, { BotFlow, recommendCans, CalcCard });
