// Calculator page — paint coverage calculator with live preview.

function PageCalculator() {
  const [room, setRoom] = useState({ length: 5, width: 4, height: 2.7 });
  const [walls, setWalls] = useState(true);
  const [ceiling, setCeiling] = useState(true);
  const [doors, setDoors] = useState(2);
  const [windows, setWindows] = useState(2);
  const [coats, setCoats] = useState(2);
  const [coverage, setCoverage] = useState(10); // m²/L
  const [productId, setProductId] = useState('tikkurila-harmony');

  const product = PRODUCTS.find(p => p.id === productId) || PRODUCTS[0];
  const swatch = RAL_COLORS.find(c => c.ral === product.ral) || RAL_COLORS[0];

  // Calculations
  const wallArea = walls ? 2 * (room.length + room.width) * room.height : 0;
  const ceilingArea = ceiling ? room.length * room.width : 0;
  const subtractions = doors * 2 + windows * 1.5;
  const totalArea = Math.max(0, wallArea + ceilingArea - subtractions);
  const litersNeeded = (totalArea * coats) / coverage;
  const liters = Math.ceil(litersNeeded * 10) / 10;
  const cost = Math.round(liters * (product.price / parseFloat(product.sizes[0]) || 50));

  return (
    <>
      <div className="page-head">
        <div className="container">
          <div className="page-head__crumbs">
            <Link to="/">Start</Link> <Icon name="chevron-right" size={11}/> <span>Kalkulator</span>
          </div>
          <div className="page-head__title">
            <h1>Ile farby<br/><em style={{ color: 'var(--brand)', fontStyle: 'italic', fontWeight: 380 }}>naprawdę</em><br/>kupić?</h1>
            <p className="page-head__lede">
              Najczęstsza pomyłka: niedokupienie pół litra i jazda po dokładkę dwa tygodnie później —
              kiedy partia barwnika już nie pasuje. Policzmy razem, raz a dobrze.
            </p>
          </div>
        </div>
      </div>

      <section className="section">
        <div className="container">
          <div className="calc-grid">
            <div>
              <div className="calc-step">
                <div className="calc-step__no">01</div>
                <div>
                  <h3 style={{ fontSize: 28 }}>Wymiary pomieszczenia</h3>
                  <p className="text-3" style={{ fontSize: 13, marginTop: 4 }}>
                    Mierz w metrach. Sufit zazwyczaj 2.5–2.8 m.
                  </p>
                </div>
              </div>

              <div className="calc-row">
                <Field label="Długość (m)" value={room.length} min={1} max={20} step={0.1}
                  onChange={v => setRoom(r => ({ ...r, length: v }))}/>
                <Field label="Szerokość (m)" value={room.width} min={1} max={20} step={0.1}
                  onChange={v => setRoom(r => ({ ...r, width: v }))}/>
                <Field label="Wysokość (m)" value={room.height} min={2} max={5} step={0.05}
                  onChange={v => setRoom(r => ({ ...r, height: v }))}/>
              </div>

              <div className="calc-step" style={{ marginTop: 48 }}>
                <div className="calc-step__no">02</div>
                <div>
                  <h3 style={{ fontSize: 28 }}>Co malujesz?</h3>
                  <p className="text-3" style={{ fontSize: 13, marginTop: 4 }}>
                    Odznacz powierzchnie, których nie ruszasz.
                  </p>
                </div>
              </div>

              <div className="calc-row">
                <ToggleCard active={walls} onClick={() => setWalls(!walls)}
                  title="Ściany" value={wallArea.toFixed(1) + ' m²'} icon="paint-roller"/>
                <ToggleCard active={ceiling} onClick={() => setCeiling(!ceiling)}
                  title="Sufit" value={ceilingArea.toFixed(1) + ' m²'} icon="building"/>
              </div>

              <div className="calc-row">
                <Field label="Drzwi (szt)" value={doors} min={0} max={10} step={1} integer
                  onChange={setDoors}/>
                <Field label="Okna (szt)" value={windows} min={0} max={10} step={1} integer
                  onChange={setWindows}/>
                <Field label="Liczba warstw" value={coats} min={1} max={4} step={1} integer
                  onChange={setCoats}/>
              </div>

              <div className="calc-step" style={{ marginTop: 48 }}>
                <div className="calc-step__no">03</div>
                <div>
                  <h3 style={{ fontSize: 28 }}>Wybierz farbę</h3>
                  <p className="text-3" style={{ fontSize: 13, marginTop: 4 }}>
                    Wydajność z karty technicznej (m²/L).
                  </p>
                </div>
              </div>

              <div className="calc-products">
                {PRODUCTS.filter(p => p.category === 'dekoracyjne').slice(0, 4).map(p => (
                  <button key={p.id}
                    onClick={() => {
                      setProductId(p.id);
                      const m2 = parseFloat(p.coverage);
                      if (!isNaN(m2)) setCoverage(m2);
                    }}
                    className={'calc-prod' + (productId === p.id ? ' is-active' : '')}>
                    <span className="swatch" style={{
                      background: (RAL_COLORS.find(c => c.ral === p.ral) || {}).hex,
                      width: 48, height: 48, borderRadius: 8
                    }}/>
                    <span style={{ flex: 1, textAlign: 'left' }}>
                      <span style={{ display: 'block', fontWeight: 600, fontSize: 14 }}>{p.brand} {p.name}</span>
                      <span className="text-3" style={{ fontSize: 12 }}>{p.coverage} · {p.finish}</span>
                    </span>
                    {productId === p.id && (
                      <span style={{
                        width: 24, height: 24, borderRadius: 999, background: 'var(--brand)',
                        color: 'var(--brand-ink)', display: 'grid', placeItems: 'center'
                      }}>
                        <Icon name="check" size={14} stroke={2.4}/>
                      </span>
                    )}
                  </button>
                ))}
              </div>
            </div>

            <aside className="calc-result">
              <div className="calc-preview" style={{ background: swatch.hex }}>
                <div className="calc-preview__room">
                  {/* Wall */}
                  <div className="calc-preview__wall"
                    style={{ background: walls ? swatch.hex : 'var(--bg-tint)' }}/>
                  <div className="calc-preview__floor"/>
                  <div className="calc-preview__ceiling"
                    style={{ background: ceiling ? swatch.hex : 'var(--bg-tint)',
                      filter: ceiling ? 'brightness(0.92)' : 'none' }}/>
                </div>
                <div style={{
                  position: 'absolute', left: 20, top: 20,
                  fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em',
                  color: 'rgba(255,255,255,0.85)', mixBlendMode: 'difference'
                }}>
                  PODGLĄD KOLORU · RAL {product.ral}
                </div>
              </div>

              <div className="calc-result__sticky">
                <div className="text-mono text-3" style={{ fontSize: 11, letterSpacing: '0.16em',
                  textTransform: 'uppercase', marginBottom: 12 }}>Wynik</div>
                <div style={{
                  fontFamily: 'var(--font-display)', fontSize: 88, fontWeight: 470,
                  letterSpacing: '-0.025em', lineHeight: 0.95, color: 'var(--ink)'
                }}>
                  {liters.toFixed(1)}<span style={{ fontStyle: 'italic', color: 'var(--brand)',
                    fontWeight: 380, fontSize: 56 }}> l</span>
                </div>
                <div className="text-2" style={{ fontSize: 14, marginTop: 8 }}>
                  Tyle farby potrzebujesz na <strong>{totalArea.toFixed(1)} m²</strong> w {coats} warstwach.
                </div>

                <hr className="divider" style={{ marginBlock: 24 }}/>

                <div className="calc-summary">
                  <Row label="Powierzchnia ścian" value={wallArea.toFixed(1) + ' m²'}/>
                  <Row label="Powierzchnia sufitu" value={ceilingArea.toFixed(1) + ' m²'}/>
                  <Row label="Odjęcie (drzwi, okna)" value={'– ' + subtractions.toFixed(1) + ' m²'}/>
                  <Row label="Wydajność" value={coverage + ' m²/L'}/>
                  <Row label="Warstwy" value={coats + 'x'}/>
                </div>

                <hr className="divider" style={{ marginBlock: 24 }}/>

                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span className="text-2" style={{ fontSize: 14 }}>Szacowany koszt</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500 }}>
                    ~{cost} zł
                  </span>
                </div>
                <p className="text-3" style={{ fontSize: 12, marginTop: 6, lineHeight: 1.5 }}>
                  Cena orientacyjna na podstawie {product.brand} {product.name}.
                  Zalecamy zakup z 10% zapasu.
                </p>

                <Link to="/katalog" className="btn btn--primary"
                  style={{ width: '100%', justifyContent: 'center', marginTop: 24 }}>
                  Dodaj do koszyka <Icon name="cart" size={14}/>
                </Link>
                <button className="btn btn--ghost"
                  style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>
                  Zapisz kalkulację (PDF)
                </button>
              </div>
            </aside>
          </div>
        </div>
      </section>

      <style>{`
        .calc-grid {
          display: grid; grid-template-columns: 1fr 420px;
          gap: var(--space-7);
          align-items: start;
        }
        .calc-step {
          display: flex; gap: 20px; align-items: center;
          padding-bottom: 20px; margin-bottom: 24px;
          border-bottom: var(--hairline);
        }
        .calc-step__no {
          width: 56px; height: 56px;
          border-radius: 999px;
          background: var(--brand-soft); color: var(--brand);
          font-family: var(--font-display); font-size: 22px; font-weight: 500;
          display: grid; place-items: center; flex: 0 0 56px;
        }
        .calc-row {
          display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;
          margin-bottom: 16px;
        }
        .calc-row:has(> :nth-child(2):last-child) { grid-template-columns: repeat(2, 1fr); }
        .calc-products {
          display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
        }
        .calc-prod {
          display: flex; align-items: center; gap: 12px;
          padding: 14px;
          background: var(--bg-elev);
          border: 2px solid var(--line);
          border-radius: var(--r-md);
          transition: 200ms ease;
        }
        .calc-prod:hover { border-color: var(--ink-3); }
        .calc-prod.is-active { border-color: var(--brand); background: var(--brand-soft); }

        .calc-result { position: sticky; top: 80px; }
        .calc-preview {
          aspect-ratio: 1;
          border-radius: var(--r-lg);
          margin-bottom: 16px;
          position: relative;
          overflow: hidden;
          transition: background 400ms ease;
        }
        .calc-preview__room {
          position: absolute; inset: 0;
          perspective: 800px;
        }
        .calc-preview__wall {
          position: absolute; left: 15%; right: 15%; top: 15%; bottom: 25%;
          transition: 400ms ease;
        }
        .calc-preview__ceiling {
          position: absolute; left: 5%; right: 5%; top: 0; height: 18%;
          clip-path: polygon(0 0, 100% 0, 88% 100%, 12% 100%);
          transition: 400ms ease;
        }
        .calc-preview__floor {
          position: absolute; left: 5%; right: 5%; bottom: 0; height: 28%;
          background: rgba(20,17,13,0.4);
          clip-path: polygon(12% 0, 88% 0, 100% 100%, 0 100%);
        }
        .calc-result__sticky {
          background: var(--bg-elev);
          border: var(--hairline);
          border-radius: var(--r-lg);
          padding: 28px;
          box-shadow: var(--sh-2);
        }
        .calc-summary { display: flex; flex-direction: column; gap: 8px; }

        @media (max-width: 980px) {
          .calc-grid { grid-template-columns: 1fr; }
          .calc-result { position: static; }
        }
        @media (max-width: 600px) {
          .calc-row { grid-template-columns: 1fr 1fr; }
          .calc-products { grid-template-columns: 1fr; }
        }
      `}</style>
    </>
  );
}

function Field({ label, value, min, max, step, onChange, integer }) {
  return (
    <div>
      <label className="label">{label}</label>
      <div style={{ position: 'relative' }}>
        <input type="number" className="input"
          value={value} min={min} max={max} step={step}
          onChange={e => {
            const v = integer ? parseInt(e.target.value) : parseFloat(e.target.value);
            if (!isNaN(v)) onChange(Math.max(min, Math.min(max, v)));
          }}/>
        <div style={{ position: 'absolute', right: 6, top: 6, bottom: 6,
          display: 'flex', flexDirection: 'column', gap: 1 }}>
          <button onClick={() => onChange(Math.min(max, value + step))}
            style={{ flex: 1, width: 24, border: 0, background: 'var(--bg-tint)',
              borderRadius: 4, color: 'var(--ink-2)' }}>
            <Icon name="plus" size={10}/>
          </button>
          <button onClick={() => onChange(Math.max(min, value - step))}
            style={{ flex: 1, width: 24, border: 0, background: 'var(--bg-tint)',
              borderRadius: 4, color: 'var(--ink-2)' }}>
            <Icon name="minus" size={10}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function ToggleCard({ active, onClick, title, value, icon }) {
  return (
    <button onClick={onClick}
      style={{
        display: 'flex', gap: 12, alignItems: 'center',
        padding: 14,
        background: active ? 'var(--brand-soft)' : 'var(--bg-elev)',
        border: '2px solid ' + (active ? 'var(--brand)' : 'var(--line)'),
        borderRadius: 'var(--r-md)',
        cursor: 'pointer', transition: '200ms ease',
      }}>
      <span style={{
        width: 40, height: 40, borderRadius: 999,
        background: active ? 'var(--brand)' : 'var(--bg-tint)',
        color: active ? 'var(--brand-ink)' : 'var(--ink-2)',
        display: 'grid', placeItems: 'center'
      }}>
        <Icon name={icon} size={18}/>
      </span>
      <span style={{ flex: 1, textAlign: 'left' }}>
        <span style={{ display: 'block', fontWeight: 600, fontSize: 14 }}>{title}</span>
        <span className="text-3" style={{ fontSize: 12 }}>{value}</span>
      </span>
      <span style={{
        width: 22, height: 22, borderRadius: 999,
        border: '2px solid ' + (active ? 'var(--brand)' : 'var(--line-2)'),
        background: active ? 'var(--brand)' : 'transparent',
        display: 'grid', placeItems: 'center'
      }}>
        {active && <Icon name="check" size={12} stroke={2.6} style={{ color: 'var(--brand-ink)' }}/>}
      </span>
    </button>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
      <span className="text-2">{label}</span>
      <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 500 }}>{value}</span>
    </div>
  );
}

window.PageCalculator = PageCalculator;
