// Interactive home configurator
const { useState: useStateCfg, useMemo: useMemoCfg } = React;

function HomeConfigurator({ addToCart, setPage }) {
  const MODULE = 625; // mm
  const [widthMods, setWidthMods] = useStateCfg(14); // 14 × 625 = 8750mm
  const [depthMods, setDepthMods] = useStateCfg(10); // 10 × 625 = 6250mm
  const [roof, setRoof] = useStateCfg("sedlova");
  const [windows, setWindows] = useStateCfg(6);
  const [doors, setDoors] = useStateCfg(2);
  const [added, setAdded] = useStateCfg(false);

  const widthMm = widthMods * MODULE;
  const depthMm = depthMods * MODULE;
  const area = (widthMm * depthMm) / 1_000_000; // m²
  const perimeter = 2 * (widthMm + depthMm) / 1000; // m
  const ribsCount = 2 * (widthMods + 1) + 2 * (depthMods + 1) - 4; // corners counted once

  const roofMul = { plocha:1.0, sedlova:1.08, pultova:1.05, valbova:1.12 };
  const basePrice = Math.round(area * 3500 * roofMul[roof]);
  const openingsPrice = windows * 3800 + doors * 5400;
  const total = basePrice + openingsPrice;

  const ribs = ribsCount;
  const uProfile = Math.ceil(perimeter / 6); // 6m profils
  const screws = ribs * 14;

  const handleAdd = () => {
    const custom = {
      id: `cfg-${Date.now()}`,
      cat: "stavebnice",
      color: "a",
      name: `Stavebnice ${(widthMm/1000).toFixed(2)} × ${(depthMm/1000).toFixed(2)} m`,
      desc: `Konfigurace z webu — ${roof}, ${windows}× okno, ${doors}× dveře`,
      price: total,
      unit: "kpl",
      sku: `CFG-${widthMods}x${depthMods}`,
      tag: "KONFIG",
    };
    addToCart(custom);
    setAdded(true);
    setTimeout(()=>setAdded(false), 1800);
  };

  // Render floorplan
  const maxMm = Math.max(widthMm, depthMm);
  const scale = 380 / maxMm;
  const pw = widthMm * scale;
  const pd = depthMm * scale;
  const cx = 220, cy = 160;
  const x0 = cx - pw/2, y0 = cy - pd/2;

  // Distribute windows/doors on perimeter
  const openings = [];
  const bays = widthMods;
  for (let i = 0; i < windows; i++) {
    const side = i % 2 === 0 ? "top" : "bottom";
    const slot = 2 + (Math.floor(i/2) * 3);
    if (slot < bays - 1) {
      if (side === "top") openings.push({ x: x0 + slot * MODULE * scale, y: y0 - 3, w: MODULE * scale * 1.5, h: 6, kind:"w" });
      else openings.push({ x: x0 + slot * MODULE * scale, y: y0 + pd - 3, w: MODULE * scale * 1.5, h: 6, kind:"w" });
    }
  }
  for (let i = 0; i < doors; i++) {
    const slot = 1 + i * (bays - 3);
    const yPos = i === 0 ? y0 + pd - 3 : y0 - 3;
    openings.push({ x: x0 + slot * MODULE * scale, y: yPos, w: MODULE * scale, h: 6, kind:"d" });
  }

  return (
    <section className="section app" style={{paddingTop:0}} id="konfigurator">
      <div className="sec-head">
        <div className="sec-head-text">
          <span className="eyebrow">Spočítejte si konstrukci</span>
          <h2 className="h2">Spočítejte první návrh nosné konstrukce za pár kliků.</h2>
          <p>Upravte rozměry, typ střechy, okna a dveře. Konfigurátor průběžně počítá výkaz prvků a orientační cenu. Výstup je orientační — finální řešení poté ověřuje projektant nebo statik.</p>
        </div>
      </div>

      <div className="cfg">
        {/* Left: canvas */}
        <div className="cfg-canvas">
          <div className="grid-bg"></div>
          <div className="hv-badge"><span className="dot"></span>2D půdorys · rastr 625 mm</div>

          <svg viewBox="0 0 440 340" style={{position:"relative",zIndex:2,width:"100%",height:"100%"}}>
            {/* grid raster overlay inside house */}
            <defs>
              <pattern id="raster" x={x0} y={y0} width={MODULE*scale} height={MODULE*scale} patternUnits="userSpaceOnUse">
                <path d={`M ${MODULE*scale} 0 L 0 0 0 ${MODULE*scale}`} fill="none" stroke="var(--primary)" strokeOpacity=".14" strokeWidth="0.6"/>
              </pattern>
            </defs>
            {/* fill */}
            <rect x={x0} y={y0} width={pw} height={pd} fill="var(--primary-soft)" fillOpacity=".35"/>
            <rect x={x0} y={y0} width={pw} height={pd} fill="url(#raster)"/>
            {/* ribs */}
            {Array.from({length: widthMods+1}).map((_,i) => (
              <line key={"vt"+i} x1={x0 + i*MODULE*scale} y1={y0} x2={x0 + i*MODULE*scale} y2={y0+pd} stroke="var(--primary)" strokeOpacity=".45" strokeWidth="0.8"/>
            ))}
            {Array.from({length: depthMods+1}).map((_,i) => (
              <line key={"hz"+i} x1={x0} y1={y0 + i*MODULE*scale} x2={x0+pw} y2={y0 + i*MODULE*scale} stroke="var(--primary)" strokeOpacity=".14" strokeWidth="0.5"/>
            ))}
            {/* outer walls */}
            <rect x={x0} y={y0} width={pw} height={pd} fill="none" stroke="var(--fg)" strokeWidth="2"/>
            {/* openings */}
            {openings.map((o,i)=>(
              <rect key={i} x={o.x} y={o.y} width={o.w} height={o.h} fill={o.kind==="w"?"var(--accent)":"var(--primary)"} stroke="var(--fg)" strokeWidth="0.5"/>
            ))}
            {/* dim top */}
            <line x1={x0} y1={y0-16} x2={x0+pw} y2={y0-16} stroke="var(--muted)" strokeWidth="0.6"/>
            <line x1={x0} y1={y0-20} x2={x0} y2={y0-12} stroke="var(--muted)"/>
            <line x1={x0+pw} y1={y0-20} x2={x0+pw} y2={y0-12} stroke="var(--muted)"/>
            <text x={x0+pw/2} y={y0-22} textAnchor="middle" fontFamily="ui-monospace" fontSize="10" fill="var(--muted)">{(widthMm/1000).toFixed(2).replace('.',',')} m · {widthMods} × 625</text>
            {/* dim right */}
            <line x1={x0+pw+16} y1={y0} x2={x0+pw+16} y2={y0+pd} stroke="var(--muted)" strokeWidth="0.6"/>
            <text x={x0+pw+22} y={y0+pd/2} fontFamily="ui-monospace" fontSize="10" fill="var(--muted)" style={{writingMode:"vertical-rl"}}>{(depthMm/1000).toFixed(2).replace('.',',')} m</text>
            {/* roof overlay */}
            {roof !== "plocha" && (
              <>
                <line x1={x0} y1={y0} x2={x0+pw/2} y2={y0+8} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>
                <line x1={x0+pw} y1={y0} x2={x0+pw/2} y2={y0+8} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>
                <line x1={x0} y1={y0+pd} x2={x0+pw/2} y2={y0+pd-8} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>
                <line x1={x0+pw} y1={y0+pd} x2={x0+pw/2} y2={y0+pd-8} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3"/>
              </>
            )}
          </svg>

          <div className="cfg-legend">
            <span><i style={{background:"var(--accent)"}}></i>Okno</span>
            <span><i style={{background:"var(--primary)"}}></i>Dveře</span>
            <span><i style={{background:"var(--primary-soft)"}}></i>Raster 625</span>
          </div>
        </div>

        {/* Right: controls */}
        <div className="cfg-panel">
          <div className="cfg-row">
            <div className="cfg-row-hd">
              <label>Šířka domu</label>
              <span className="cfg-val">{(widthMm/1000).toFixed(2).replace('.',',')} m <em>({widthMods} × 625)</em></span>
            </div>
            <input type="range" min="6" max="20" value={widthMods} onChange={e=>setWidthMods(+e.target.value)}/>
          </div>

          <div className="cfg-row">
            <div className="cfg-row-hd">
              <label>Hloubka domu</label>
              <span className="cfg-val">{(depthMm/1000).toFixed(2).replace('.',',')} m <em>({depthMods} × 625)</em></span>
            </div>
            <input type="range" min="6" max="16" value={depthMods} onChange={e=>setDepthMods(+e.target.value)}/>
          </div>

          <div className="cfg-row">
            <div className="cfg-row-hd">
              <label>Typ střechy</label>
              <span className="cfg-val">&nbsp;</span>
            </div>
            <div className="cfg-chips">
              {[["plocha","Plochá"],["sedlova","Sedlová"],["pultova","Pultová"],["valbova","Valbová"]].map(([id,l])=>(
                <button key={id} className={"cfg-chip"+(roof===id?" active":"")} onClick={()=>setRoof(id)}>{l}</button>
              ))}
            </div>
          </div>

          <div className="cfg-grid2">
            <div className="cfg-row">
              <div className="cfg-row-hd"><label>Okna</label><span className="cfg-val">{windows}×</span></div>
              <div className="qty-ctrl" style={{alignSelf:"flex-start"}}>
                <button onClick={()=>setWindows(Math.max(0,windows-1))}>−</button>
                <div className="qty-val">{windows}</div>
                <button onClick={()=>setWindows(Math.min(16,windows+1))}>+</button>
              </div>
            </div>
            <div className="cfg-row">
              <div className="cfg-row-hd"><label>Dveře</label><span className="cfg-val">{doors}×</span></div>
              <div className="qty-ctrl" style={{alignSelf:"flex-start"}}>
                <button onClick={()=>setDoors(Math.max(1,doors-1))}>−</button>
                <div className="qty-val">{doors}</div>
                <button onClick={()=>setDoors(Math.min(4,doors+1))}>+</button>
              </div>
            </div>
          </div>

          <div className="cfg-bom">
            <h6>Výkaz prvků <span>· orientační</span></h6>
            <div className="bom-row"><span>Zastavěná plocha</span><b>{area.toFixed(1).replace('.',',')} m²</b></div>
            <div className="bom-row"><span>Obvod</span><b>{perimeter.toFixed(1).replace('.',',')} m</b></div>
            <div className="bom-row"><span>Nosná žebra</span><b>{ribs} ks</b></div>
            <div className="bom-row"><span>U profily (6 m)</span><b>{uProfile*2} ks</b></div>
            <div className="bom-row"><span>Kotvící prvky</span><b>cca {screws} ks</b></div>
          </div>

          {/* Buildability score */}
          {(() => {
            const openingCount = windows + doors;
            const openingsPerWall = Math.ceil(openingCount / 4);
            const checks = [
              { ok: widthMods >= 8 && depthMods >= 6, label: "Modulové rozměry v rozsahu systému", warn: "Velmi malý dům — zvažte studio či přístavbu" },
              { ok: openingsPerWall <= 3, label: "Otvorů na stěnu v normě", warn: "Vysoký počet otvorů na jedné stěně — kontrola statikem" },
              { ok: roof !== "valbova" || area <= 100, label: "Střecha vhodná pro plochu", warn: "Valbová střecha pro velký dům — vyžaduje úpravu" },
              { ok: doors >= 1, label: "Minimálně jedny dveře", warn: "Návrh musí mít alespoň jedny vstupní dveře" },
              { ok: true, label: "Rastr 625 mm zachován", warn: "" },
            ];
            const okCount = checks.filter(c=>c.ok).length;
            const score = Math.round((okCount / checks.length) * 100);
            const status = score === 100 ? "Připraveno k odeslání" : score >= 80 ? "Téměř hotovo" : "Vyžaduje úpravy";
            return (
              <div className="bs">
                <div className="bs-hd">
                  <h6>Kontrola návrhu</h6>
                  <div className="bs-score">{score} % · {status}</div>
                </div>
                <div className="bs-bar"><div className="bs-bar-fill" style={{width: `${score}%`}}/></div>
                <div className="bs-checks">
                  {checks.map((c,i)=>(
                    <div key={i} className={"bs-check"+(c.ok?"":" muted")}>
                      <span className={"ic "+(c.ok?"ok":"warn")}>{c.ok?"✓":"!"}</span>
                      <span>{c.ok ? c.label : (c.warn || c.label)}</span>
                    </div>
                  ))}
                </div>
              </div>
            );
          })()}

          <div className="cfg-price">
            <div>
              <div className="muted" style={{fontSize:12,fontFamily:"var(--font-mono)",textTransform:"uppercase",letterSpacing:".08em"}}>Orientační cena konstrukce</div>
              <div className="cfg-price-big">{total.toLocaleString("cs-CZ")} Kč</div>
              <div className="muted" style={{fontSize:12}}>bez DPH · {(total*1.21).toLocaleString("cs-CZ",{maximumFractionDigits:0})} Kč s DPH · finální cenu potvrdíme podle projektu</div>
            </div>
            <button className={"btn accent"+(added?" added":"")} onClick={handleAdd}>
              {added ? "✓ Návrh uložen" : "Uložit návrh a nacenit →"}
            </button>
          </div>

          <div className="cfg-foot">
            <span className="muted" style={{fontSize:12}}>Máte vlastní půdorys? Pošlete nám ho a ověříme, jak sedí do systému.</span>
            <button className="linkish" onClick={()=>setPage("kontakt")}>Poslat půdorys →</button>
          </div>
        </div>
      </div>
    </section>
  );
}

window.HomeConfigurator = HomeConfigurator;
