const { useState, useEffect, useMemo, useRef } = React;

/* --------------- Constantes --------------- */

const MATERIAL_CONFIG = {
  wallpanel: { label: "Wall Panel", sub: "Varillas de la pared", default: "Chocolate Walnut" },
  pvc:       { label: "Placa PVC", sub: "Panel detrás del TV",   default: "Calacata" },
  melamina:  { label: "Melamina",  sub: "Mueble y torre",         default: "Ebano Negro" },
};

const ORDER = ["wallpanel", "pvc", "melamina"]; // izquierda → derecha

function pvcKey(m) { return m.sub ? `${m.name} · ${m.sub}` : m.name; }
function matKey(m, cat) { return cat === "pvc" ? pvcKey(m) : m.name; }

/* --------------- App --------------- */

function App() {
  const M = window.MATERIALS;

  const persisted = (() => {
    try { return JSON.parse(localStorage.getItem("shd_combo_v1") || "{}"); } catch { return {}; }
  })();

  const [view, setView] = useState(persisted.view || "muestrario"); // muestrario | mueble
  const [sel, setSel] = useState({
    wallpanel: persisted.wallpanel || MATERIAL_CONFIG.wallpanel.default,
    pvc:       persisted.pvc       || MATERIAL_CONFIG.pvc.default,
    melamina:  persisted.melamina  || MATERIAL_CONFIG.melamina.default,
  });
  const [pvcSub, setPvcSub] = useState(persisted.pvcSub || "Texturada");
  const [openCat, setOpenCat] = useState(null);  // cat actualmente seleccionado en bottom sheet

  useEffect(() => {
    localStorage.setItem("shd_combo_v1", JSON.stringify({ ...sel, pvcSub, view }));
  }, [sel, pvcSub, view]);

  const current = {
    wallpanel: M.wallpanel.find(m => m.name === sel.wallpanel) || M.wallpanel[0],
    pvc:       M.pvc.find(m => pvcKey(m) === sel.pvc) || M.pvc.find(m => m.sub === pvcSub) || M.pvc[0],
    melamina:  M.melamina.find(m => m.name === sel.melamina) || M.melamina[0],
  };

  const pickMaterial = (cat, value) => {
    setSel(s => ({ ...s, [cat]: value }));
  };

  return (
    <div className="app">
      <TopBar current={current} />

      <Muestrario current={current} onPickCat={setOpenCat} />

      {openCat && (
        <Selector
          cat={openCat}
          current={current[openCat]}
          onClose={() => setOpenCat(null)}
          onPick={(val) => pickMaterial(openCat, val)}
          pvcSub={pvcSub} setPvcSub={setPvcSub}
        />
      )}
    </div>
  );
}

/* --------------- Top bar --------------- */

function TopBar({ current }) {
  const doShare = async () => {
    try {
      // fallback: open download helper modal
      alert("Para guardar la combinación: tomá una captura de pantalla con tu celular 📸\n\n" +
            "Wall Panel: " + current.wallpanel.name + "\n" +
            "PVC: " + (current.pvc.sub ? current.pvc.name + " · " + current.pvc.sub : current.pvc.name) + "\n" +
            "Melamina: " + current.melamina.name);
    } catch {}
  };

  return (
    <header className="topbar">
      <div className="topbar__brand">
        <img src="assets/logo.png" alt="" onError={(e)=>e.target.style.display='none'} />
        <div>
          <div className="topbar__name">Soul Home Deco</div>
          <div className="topbar__tag">Combinador de materiales</div>
        </div>
      </div>
      <div className="topbar__actions">
        <button className="iconbtn" onClick={doShare} aria-label="Compartir">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
        </button>
      </div>
    </header>
  );
}

/* --------------- Muestrario (3 paneles) --------------- */

function Muestrario({ current, onPickCat }) {
  return (
    <main className="muestrario">
      {ORDER.map((cat) => {
        const mat = current[cat];
        const cfg = MATERIAL_CONFIG[cat];
        return (
          <button
            key={cat}
            className={`strip strip--${cat}`}
            onClick={() => onPickCat(cat)}
            aria-label={`Elegir ${cfg.label}`}
          >
            <span
              className="strip__tex"
              style={{ backgroundImage: `url("${encodeURI(mat.file)}")` }}
            />
            <span className="strip__dim" />
            <span className="strip__grain" aria-hidden />
            <span className="strip__tag">
              <span className="strip__cat">{cfg.label}</span>
              <span className="strip__name">{mat.name}{cat==="pvc" && mat.sub ? <span className="strip__sub"> · {mat.sub}</span> : null}</span>
              <span className="strip__hint">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                tocá para cambiar
              </span>
            </span>
          </button>
        );
      })}
    </main>
  );
}

/* --------------- Bottom info bar --------------- */

function BottomInfo({ current }) {
  return (
    <div className="bottominfo">
      {ORDER.map(cat => {
        const mat = current[cat];
        return (
          <div key={cat} className="bottominfo__item">
            <span className="bottominfo__swatch" style={{ backgroundImage: `url("${encodeURI(mat.file)}")` }} />
            <span className="bottominfo__text">
              <span className="bottominfo__cat">{MATERIAL_CONFIG[cat].label}</span>
              <span className="bottominfo__name">{mat.name}</span>
            </span>
          </div>
        );
      })}
    </div>
  );
}

/* --------------- Selector (bottom sheet) --------------- */

function Selector({ cat, current, onClose, onPick, pvcSub, setPvcSub }) {
  const M = window.MATERIALS;
  const cfg = MATERIAL_CONFIG[cat];
  const [query, setQuery] = useState("");

  useEffect(() => {
    // bloqueo scroll body
    document.body.classList.add("no-scroll");
    return () => document.body.classList.remove("no-scroll");
  }, []);

  const list = useMemo(() => {
    let arr = M[cat];
    if (cat === "pvc") arr = arr.filter(m => m.sub === pvcSub);
    if (query) arr = arr.filter(m => m.name.toLowerCase().includes(query.toLowerCase()));
    return arr;
  }, [cat, pvcSub, query]);

  const activeKey = cat === "pvc" ? pvcKey(current) : current.name;

  return (
    <>
      <div className="sheet-backdrop" onClick={onClose} />
      <div className="sheet" role="dialog" aria-modal="true">
        <div className="sheet__handle" onClick={onClose} />
        <div className="sheet__head">
          <div>
            <div className="sheet__title">{cfg.label}</div>
            <div className="sheet__sub">{cfg.sub}</div>
          </div>
          <button className="sheet__close" onClick={onClose} aria-label="Cerrar">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        {cat === "pvc" && (
          <div className="sheet__pvcswitch">
            {["Texturada", "Brillante", "Opaca"].map(s => (
              <button
                key={s}
                className={pvcSub===s?"is-on":""}
                onClick={()=>setPvcSub(s)}
              >{s}</button>
            ))}
          </div>
        )}

        <div className="sheet__search">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input
            placeholder={`Buscar en ${cfg.label.toLowerCase()}`}
            value={query}
            onChange={e=>setQuery(e.target.value)}
          />
        </div>

        <div className="sheet__grid">
          {list.map(m => {
            const k = matKey(m, cat);
            const active = k === activeKey;
            return (
              <button
                key={k}
                className={`swatch ${active?"is-active":""}`}
                onClick={() => { onPick(k); }}
              >
                <span className="swatch__img" style={{ backgroundImage: `url("${encodeURI(m.file)}")` }} />
                <span className="swatch__label">{m.name}</span>
                {active && <span className="swatch__check" aria-hidden>✓</span>}
              </button>
            );
          })}
          {list.length === 0 && <div className="sheet__empty">Sin resultados</div>}
        </div>
      </div>
    </>
  );
}

/* --------------- Mueble view (vista secundaria) --------------- */

function MuebleView({ current, onPickCat }) {
  const wpColor = current.wallpanel.color || "#8b6a45";
  const mel = current.melamina.file;
  const pvc = current.pvc.file;
  const url = (p) => `url("${encodeURI(p)}")`;

  // Gradient per slat — simulates a rounded wooden slat with light on center,
  // shadow on edges, dark groove on the right.
  const slatGradient = (c) => {
    // derive dark + highlight from base color
    const parse = (hex) => {
      const h = hex.replace("#","");
      return [parseInt(h.slice(0,2),16), parseInt(h.slice(2,4),16), parseInt(h.slice(4,6),16)];
    };
    const [r,g,b] = parse(c);
    const clamp = v => Math.min(255, Math.max(0, Math.round(v)));
    const shade = (f) => `rgb(${clamp(r*f)},${clamp(g*f)},${clamp(b*f)})`;
    return `linear-gradient(90deg,
      ${shade(0.35)} 0%,
      ${shade(0.75)} 8%,
      ${c} 35%,
      ${shade(1.12)} 55%,
      ${c} 75%,
      ${shade(0.7)} 94%,
      ${shade(0.3)} 100%)`;
  };

  const slats = Array.from({ length: 40 }, (_, i) => i);
  const baseSlats = Array.from({ length: 44 }, (_, i) => i);
  const slatStyle = {
    backgroundImage: slatGradient(wpColor),
    backgroundColor: wpColor,
  };
  const floorStyle = {
    backgroundImage: `linear-gradient(180deg, rgba(0,0,0,.2), rgba(0,0,0,.05)), ${slatGradient(wpColor)}`,
    backgroundColor: wpColor,
    filter: "brightness(.82)",
  };

  return (
    <main className="mueble">
      <div className="mueble__frame">
        {/* pared */}
        <div className="m-wall" onClick={() => onPickCat("wallpanel")}>
          {slats.map(i => (
            <div key={i} className="m-slat" style={slatStyle} />
          ))}
          <span className="m-tag m-tag--wall">Wall Panel · {current.wallpanel.name}</span>
        </div>

        {/* panel tv + pvc */}
        <div className="m-pvc" onClick={(e)=>{ e.stopPropagation(); onPickCat("pvc"); }} style={{ backgroundImage: url(pvc) }}>
          <div className="m-tv">
            <div className="m-tv__screen" />
          </div>
          <span className="m-tag m-tag--pvc">PVC · {current.pvc.name}{current.pvc.sub?" · "+current.pvc.sub:""}</span>
        </div>

        {/* mueble bajo */}
        <div className="m-rack" onClick={(e)=>{ e.stopPropagation(); onPickCat("melamina"); }} style={{ backgroundImage: url(mel) }}>
          <div className="m-rack__door" />
          <div className="m-rack__door" />
          <div className="m-rack__door" />
          <span className="m-tag m-tag--mel">Melamina · {current.melamina.name}</span>
        </div>

        {/* piso */}
        <div className="m-floor">
          {baseSlats.map(i => (
            <div key={i} className="m-floorslat" style={slatStyle} />
          ))}
        </div>
      </div>
    </main>
  );
}

/* --------------- Mount --------------- */

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
