/* global React, T, Pill */
const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP } = React;

const QUADRANTS = {
  star:      { en: "Star",      es: "Estrella", color: "var(--brand-green)",  descKey: "starDesc",   recoKey: "starReco"  },
  plowhorse: { en: "Plowhorse", es: "Burro",    color: "var(--brand-blue)",   descKey: "plowDesc",   recoKey: "plowReco"  },
  puzzle:    { en: "Puzzle",    es: "Enigma",   color: "var(--brand-orange)", descKey: "puzzleDesc", recoKey: "puzzleReco"},
  dog:       { en: "Dog",       es: "Perro",    color: "var(--brand-red)",    descKey: "dogDesc",    recoKey: "dogReco"   },
};

const classify = (pop, margin) => {
  const highPop = pop >= 0.45;
  const highMar = margin >= 0.62;
  if (highPop && highMar) return "star";
  if (highPop && !highMar) return "plowhorse";
  if (!highPop && highMar) return "puzzle";
  return "dog";
};

const confidenceOf = (views) => (views >= 40 ? "high" : views >= 12 ? "med" : "low");

const PricingTab = ({ lang, agg, menu }) => {
  const t = T[lang];

  // Real popularity: match each published menu item to its real view count.
  const viewsByName = useMemoP(() => {
    const m = {};
    if (agg && agg.topViewed) agg.topViewed.forEach((v) => { m[v.name] = v.count; });
    return m;
  }, [agg]);

  // cost % is a genuine user input (not tracked) — seed at 30%, editable.
  const [costs, setCosts] = useStateP({});
  const [prices, setPrices] = useStateP({});

  useEffectP(() => {
    setCosts((prev) => {
      const next = { ...prev };
      (menu || []).forEach((it) => { if (next[it.id] == null) next[it.id] = 30; });
      return next;
    });
    setPrices((prev) => {
      const next = { ...prev };
      (menu || []).forEach((it) => { if (next[it.id] == null) next[it.id] = Number(it.price) || 0; });
      return next;
    });
  }, [menu]);

  const enriched = useMemoP(() => {
    const list = (menu || []).map((it) => ({
      id: it.id,
      name: it.name,
      price: prices[it.id] != null ? prices[it.id] : Number(it.price) || 0,
      cost: costs[it.id] != null ? costs[it.id] : 30,
      views: viewsByName[it.name] || 0,
    }));
    const maxViews = Math.max(1, ...list.map((i) => i.views));
    return list.map((it) => {
      const margin = it.price > 0 ? (it.price - (it.price * it.cost / 100)) / it.price : 0;
      const popularity = it.views / maxViews;
      const tag = classify(popularity, margin);
      return { ...it, margin, popularity, tag, confidence: confidenceOf(it.views) };
    }).sort((a, b) => b.views - a.views);
  }, [menu, prices, costs, viewsByName]);

  const [hovered, setHovered] = useStateP(null);

  const counts = useMemoP(() => {
    const c = { star: 0, plowhorse: 0, puzzle: 0, dog: 0 };
    enriched.forEach((i) => c[i.tag]++);
    return c;
  }, [enriched]);

  const hasData = enriched.length > 0 && agg && agg.hasData && agg.totalViews > 0;

  const plowCount = counts.plowhorse, dogCount = counts.dog;
  const summaryEN = `${plowCount > 0 ? `${plowCount} item${plowCount>1?"s are":" is"} underpriced relative to demand. ` : ""}${dogCount > 0 ? `${dogCount} item${dogCount>1?"s are":" is"} a drag on your menu — consider hiding or removing ${dogCount>1?"them":"it"}.` : "No underperformers — healthy spread."}`;
  const summaryES = `${plowCount > 0 ? `${plowCount} ${plowCount>1?"platos están":"plato está"} infravalorado${plowCount>1?"s":""} respecto a la demanda. ` : ""}${dogCount > 0 ? `${dogCount} ${dogCount>1?"platos lastran":"plato lastra"} tu carta — considera esconderlo${dogCount>1?"s":""} o retirarlo${dogCount>1?"s":""}.` : "Sin bajos rendimientos — buena distribución."}`;
  const summary = lang === "es" ? summaryES : summaryEN;

  const updateCost = (id, v) => setCosts((p) => ({ ...p, [id]: Math.max(0, Number(v) || 0) }));
  const updatePrice = (id, v) => setPrices((p) => ({ ...p, [id]: Math.max(0, Number(v) || 0) }));

  if ((menu || []).length === 0) {
    return (
      <div className="panel" style={{textAlign:"center", padding:"60px 24px", color:"var(--text-muted)"}}>
        {lang === "es"
          ? "Publica tu menú en la pestaña Menú & QR para clasificar tus platos por popularidad real y margen."
          : "Publish your menu in the Menu & QR tab to plot your dishes by real popularity and margin."}
      </div>
    );
  }

  return (
    <>
      {!hasData && (
        <div className="data-banner">
          {lang === "es"
            ? "La popularidad se basa en vistas reales. Aún no hay vistas en este periodo — la matriz se llenará a medida que lleguen escaneos."
            : "Popularity is based on real item views. No views in this period yet — the matrix fills in as scans arrive."}
        </div>
      )}

      <div className="price-summary">{summary}</div>

      <div className="matrix-card">
        <div className="panel-head" style={{marginBottom:24}}>
          <div>
            <div className="panel-title">{t.matrixTitle}</div>
            <div className="panel-sub">{t.matrixSub}</div>
          </div>
          <Pill color="var(--brand-green)">{lang==="es"?"datos reales":"real data"}</Pill>
        </div>

        <div className="matrix-wrap">
          <div className="matrix-axis-y">{t.marAxis}</div>
          <div className="matrix-axis-x">{t.popAxis}</div>

          <div className="matrix-grid">
            <div className="matrix-q tl"><div className="lbl">{t.puzzle.toUpperCase()}</div></div>
            <div className="matrix-q tr"><div className="lbl">{t.star.toUpperCase()}</div></div>
            <div className="matrix-q bl"><div className="lbl">{t.dog.toUpperCase()}</div></div>
            <div className="matrix-q br"><div className="lbl">{t.plowhorse.toUpperCase()}</div></div>

            {enriched.map((it, i) => {
              const q = QUADRANTS[it.tag];
              return (
                <div
                  key={it.id}
                  className="matrix-dot"
                  style={{ left: `${it.popularity * 100}%`, bottom: `${it.margin * 100}%`, "--c": q.color }}
                  onMouseEnter={() => setHovered(i)}
                  onMouseLeave={() => setHovered(null)}
                >
                  <div className="d"/>
                  <div className="lbl">{it.name.split(" ")[0]}</div>
                  {hovered === i && (
                    <div className="matrix-tooltip">
                      <div className="tt-t">{it.name}</div>
                      <div className="tt-r"><span>{lang==="es"? QUADRANTS[it.tag].es : QUADRANTS[it.tag].en}</span><span>{t[q.descKey].split(".")[0]}</span></div>
                      <div className="tt-r"><span>{t.lblViews}</span><span>{it.views}</span></div>
                      <div className="tt-r"><span>price</span><span>€{it.price.toFixed(2)}</span></div>
                      <div className="tt-r"><span>cost</span><span>{it.cost}%</span></div>
                      <div className="tt-r"><span>{t.lblMargin}</span><span>{Math.round(it.margin*100)}%</span></div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        <div className="matrix-legend">
          {["star","plowhorse","puzzle","dog"].map((k) => {
            const q = QUADRANTS[k];
            const label = lang === "es" ? q.es : q.en;
            return (
              <div key={k} className="legend-item">
                <div className="sw" style={{background:q.color}}/>
                <div>
                  <div style={{fontWeight:600, marginBottom:2}}>{label} <span style={{color:"var(--text-muted)", fontWeight:400}}>· {counts[k]}</span></div>
                  <div style={{color:"var(--text-muted)", fontSize:13}}>{t[q.descKey]}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="item-grid">
        {enriched.map((it) => {
          const q = QUADRANTS[it.tag];
          const label = lang === "es" ? q.es : q.en;
          const confLabel = it.confidence === "high" ? t.confHigh : it.confidence === "med" ? t.confMed : t.confLow;
          return (
            <div key={it.id} className="item-card">
              <div className="item-head">
                <div className="item-name">{it.name}</div>
                <span className="quad-badge" style={{background:q.color}}>{label}</span>
              </div>
              <div className="chip-row">
                <span className="chip"><b>{it.views}</b> {t.lblViews}</span>
                <span className="chip"><b>{Math.round(it.margin*100)}%</b> {t.lblMargin}</span>
              </div>
              <div className="input-row">
                <div className="field">
                  <label>{t.lblPrice}</label>
                  <input type="number" step="0.50" value={it.price} onChange={(e)=>updatePrice(it.id, e.target.value)}/>
                </div>
                <div className="field">
                  <label>{t.lblCost}</label>
                  <input type="number" step="1" value={it.cost} onChange={(e)=>updateCost(it.id, e.target.value)}/>
                </div>
              </div>
              <div className="advisor-block" style={{"--c":q.color}}>
                {t[q.recoKey]}
              </div>
              <div className="confidence">
                <div className={`conf-dot on ${it.confidence}`}/>
                <div className={`conf-dot ${it.confidence !== "low" ? "on" : ""} ${it.confidence}`}/>
                <div className={`conf-dot ${it.confidence === "high" ? "on" : ""} ${it.confidence}`}/>
                <span>{confLabel}</span>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
};

Object.assign(window, { PricingTab });
