// Interactive mini configurator — redesigned light theme

const PRODUCTS = [
  { id: 'ceg', name: 'Cegła klinkierowa', code: 'CEG', formats: ['250×120×65', '250×120×85', '290×140×65'], unit: 'szt.', perPallet: 480, basePrice: 2.40 },
  { id: 'plt', name: 'Płytka elewacyjna',  code: 'PLT', formats: ['245×65×9', '245×65×14', '210×52×9'],   unit: 'm²',  perPallet: 36,  basePrice: 89.00 },
  { id: 'ksz', name: 'Kształtka narożna',  code: 'KSZ', formats: ['115×115×65', '90×115×65'],              unit: 'szt.', perPallet: 240, basePrice: 4.80 },
  { id: 'drg', name: 'Klinkier drogowy',   code: 'DRG', formats: ['200×100×52', '220×110×52'],            unit: 'm²',  perPallet: 12,  basePrice: 124.00 },
];

const COLORS = [
  { id: 'czerwony',   label: 'Czerwony',   code: 'R-01', swatch: '#9e2b1d', mortar: '#d8d1c4', stockDays: 0 },
  { id: 'naturalny',  label: 'Naturalny',  code: 'N-02', swatch: '#b56a4a', mortar: '#e2dcce', stockDays: 0 },
  { id: 'grafitowy',  label: 'Grafitowy',  code: 'G-03', swatch: '#3a3633', mortar: '#bfb9ad', stockDays: 0 },
  { id: 'piaskowy',   label: 'Piaskowy',   code: 'S-04', swatch: '#c8a079', mortar: '#e5dfd0', stockDays: 0 },
  { id: 'cieniowany', label: 'Cieniowany', code: 'C-05', swatch: '#6b4232', mortar: '#d4cdbd', stockDays: 3 },
  { id: 'kremowy',    label: 'Kremowy',    code: 'K-06', swatch: '#dccba9', mortar: '#ede8d8', stockDays: 5 },
];

// ----- Color helpers -----
const hexToRgb = (h) => {
  const x = h.replace('#', '');
  return [parseInt(x.slice(0, 2), 16), parseInt(x.slice(2, 4), 16), parseInt(x.slice(4, 6), 16)];
};
const rgbToHex = ([r, g, b]) => '#' + [r, g, b].map(v => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('');
const shade = (hex, amt) => {
  const [r, g, b] = hexToRgb(hex);
  return rgbToHex([r + amt, g + amt, b + amt]);
};
// Deterministic noise per (row, col) — no random()
const noise = (r, c) => (((r * 73856093) ^ (c * 19349663)) % 100) / 100 - 0.5;

// ----- Brick wall visualization -----
const BrickWall = ({ color, mortar, format, sizeW = 480, sizeH = 360 }) => {
  // Parse format e.g. "250×120×65" — face = w × h
  const parts = format.split('×').map(Number);
  const w = parts[0], h = parts[parts.length - 1];
  const faceRatio = w / h;

  const brickW = 96;
  const brickH = Math.max(18, Math.round(brickW / faceRatio));
  const gap = 3;
  const rowH = brickH + gap;

  const cols = Math.ceil(sizeW / brickW) + 2;
  const rows = Math.ceil(sizeH / rowH) + 1;

  const bricks = [];
  for (let r = 0; r < rows; r++) {
    const offset = (r % 2) * (brickW / 2);
    for (let c = -1; c < cols; c++) {
      const x = c * brickW + offset;
      const y = r * rowH;
      const n = noise(r, c);
      const variation = Math.round(n * 20); // ±10
      const brickFill = shade(color, variation);
      bricks.push({ x, y, w: brickW - gap, h: brickH, fill: brickFill });
    }
  }

  return (
    <svg viewBox={`0 0 ${sizeW} ${sizeH}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ display: 'block', background: mortar }}>
      <defs>
        <linearGradient id="brickHilite" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(255,255,255,0.18)" />
          <stop offset="40%" stopColor="rgba(255,255,255,0)" />
          <stop offset="100%" stopColor="rgba(0,0,0,0.10)" />
        </linearGradient>
        <filter id="grain">
          <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" />
          <feColorMatrix values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.15 0" />
          <feComposite in2="SourceGraphic" operator="in" />
        </filter>
      </defs>
      {bricks.map((b, i) => (
        <g key={i}>
          <rect x={b.x} y={b.y} width={b.w} height={b.h} fill={b.fill} />
          <rect x={b.x} y={b.y} width={b.w} height={b.h} fill="url(#brickHilite)" />
        </g>
      ))}
      {/* Subtle vignette */}
      <rect width={sizeW} height={sizeH} fill="url(#vignette)" pointerEvents="none" />
      <defs>
        <radialGradient id="vignette" cx="50%" cy="50%" r="75%">
          <stop offset="60%" stopColor="rgba(0,0,0,0)" />
          <stop offset="100%" stopColor="rgba(0,0,0,0.18)" />
        </radialGradient>
      </defs>
    </svg>
  );
};

// ----- Color swatch (refined) -----
const Swatch = ({ color, selected, stockDays, onClick, label, code }) => (
  <button onClick={onClick}
    style={{
      position: 'relative', border: 'none', borderRadius: 4, padding: 0, cursor: 'pointer',
      background: 'transparent', textAlign: 'left',
    }}>
    {/* Material chip — bigger, with subtle interior shadow */}
    <div style={{
      height: 72, borderRadius: 3, background: color, position: 'relative', overflow: 'hidden',
      boxShadow: selected
        ? `0 0 0 2px var(--accent), 0 0 0 5px var(--accent-soft), inset 0 -1px 0 rgba(0,0,0,.18), inset 0 1px 0 rgba(255,255,255,.12)`
        : `0 0 0 1px var(--line), inset 0 -1px 0 rgba(0,0,0,.18), inset 0 1px 0 rgba(255,255,255,.12)`,
      transition: 'box-shadow .12s',
    }}>
      {/* brick texture hint inside the chip */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage:
          `linear-gradient(0deg, rgba(0,0,0,.18) 0 1.5px, transparent 1.5px),
           linear-gradient(90deg, rgba(0,0,0,.10) 0 1.5px, transparent 1.5px)`,
        backgroundSize: '46px 22px, 46px 22px',
        backgroundPosition: '0 0, 23px 11px',
        opacity: 0.7,
      }} />
      {selected && (
        <div className="mono" style={{
          position: 'absolute', top: 6, right: 6, background: 'var(--accent)', color: '#fff',
          fontSize: 9, padding: '2px 6px', borderRadius: 2, letterSpacing: '0.06em',
        }}>WYBRANE</div>
      )}
    </div>
    <div style={{ padding: '10px 2px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
      <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{label}</span>
      <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.06em' }}>{code}</span>
    </div>
    <div className="mono" style={{
      fontSize: 10, color: stockDays === 0 ? '#1d7a4f' : 'var(--ink-4)', marginTop: 2,
      display: 'flex', alignItems: 'center', gap: 4, letterSpacing: '0.04em',
    }}>
      <span style={{
        width: 5, height: 5, borderRadius: '50%',
        background: stockDays === 0 ? '#1d7a4f' : 'var(--ink-4)',
      }} />
      {stockDays === 0 ? 'Na stanie' : `+${stockDays} dni`}
    </div>
  </button>
);

// ----- Pallet grid visualization -----
const PalletGrid = ({ pallets, total = 24, color }) => (
  <div>
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${total}, 1fr)`, gap: 3 }}>
      {Array.from({ length: total }).map((_, i) => {
        const filled = i < pallets;
        return (
          <div key={i} style={{
            height: 28, borderRadius: 2,
            background: filled ? color : 'transparent',
            border: filled ? '1px solid rgba(0,0,0,0.15)' : '1px dashed var(--line)',
            transition: 'background .15s',
            position: 'relative',
          }}>
            {filled && (
              <div style={{
                position: 'absolute', inset: 2,
                backgroundImage:
                  `linear-gradient(0deg, rgba(0,0,0,.18) 0 1px, transparent 1px 6px),
                   linear-gradient(90deg, rgba(0,0,0,.10) 0 1px, transparent 1px 8px)`,
                opacity: 0.6,
              }} />
            )}
          </div>
        );
      })}
    </div>
    <div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.06em', marginTop: 10, display: 'flex', justifyContent: 'space-between' }}>
      <span>1 PALETA</span>
      <span>24 PALETY · 1 CIĘŻARÓWKA</span>
    </div>
  </div>
);

// ----- Step header -----
const StepHead = ({ n, label, hint }) => (
  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
      <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.1em' }}>{n}</span>
      <span style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.005em' }}>{label}</span>
    </div>
    {hint && <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.06em' }}>{hint}</span>}
  </div>
);

// ----- Main configurator -----
const Configurator = ({ compact = false }) => {
  const [productId, setProductId] = React.useState('ceg');
  const [colorId, setColorId] = React.useState('czerwony');
  const [formatIdx, setFormatIdx] = React.useState(0);
  const [pallets, setPallets] = React.useState(8);

  const product = PRODUCTS.find(p => p.id === productId);
  const color = COLORS.find(c => c.id === colorId);
  const format = product.formats[formatIdx];

  const colorMultiplier = color.stockDays === 0 ? 1 : 1.05 + color.stockDays * 0.01;
  const unitPrice = product.basePrice * colorMultiplier;
  const totalUnits = pallets * product.perPallet;
  const subtotal = totalUnits * unitPrice;
  const transport = pallets <= 8 ? 0 : Math.round(pallets * 38);
  const total = subtotal + transport;
  const eta = color.stockDays === 0 ? '48 h' : `${48 + color.stockDays * 24} h`;
  const truckUsage = Math.min(100, Math.round((pallets / 24) * 100));

  const sku = `${product.code}-${color.code.replace('-', '')}-${format.split('×').slice(0, 2).join('')}`;

  return (
    <div style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
      {/* Product tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', background: 'var(--bone)' }}>
        {PRODUCTS.map(p => {
          const active = p.id === productId;
          return (
            <button key={p.id} onClick={() => { setProductId(p.id); setFormatIdx(0); }}
              style={{
                flex: 1, padding: '18px 20px', textAlign: 'left', border: 'none',
                background: active ? '#fff' : 'transparent', cursor: 'pointer',
                borderRight: '1px solid var(--line)', borderBottom: active ? '2px solid var(--accent)' : '2px solid transparent',
                marginBottom: -1, transition: 'all .12s',
              }}>
              <div className="mono" style={{ fontSize: 10, color: active ? 'var(--accent)' : 'var(--ink-4)', letterSpacing: '0.12em' }}>{p.code}</div>
              <div style={{ fontSize: 14, fontWeight: active ? 500 : 400, color: active ? 'var(--ink)' : 'var(--ink-3)', marginTop: 4 }}>{p.name}</div>
            </button>
          );
        })}
      </div>

      {/* Body — preview + controls */}
      <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : '1.1fr 1fr', minHeight: 520 }}>
        {/* LEFT — visual */}
        <div style={{ position: 'relative', borderRight: '1px solid var(--line)', background: color.mortar, minHeight: compact ? 280 : 'auto' }}>
          <BrickWall color={color.swatch} mortar={color.mortar} format={format} />
          {/* Top-left meta */}
          <div style={{ position: 'absolute', top: 16, left: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span className="mono" style={{
              background: 'rgba(255,255,255,0.92)', color: 'var(--ink-2)', padding: '4px 8px',
              fontSize: 10, borderRadius: 2, letterSpacing: '0.08em',
            }}>
              {product.code} · {color.label.toUpperCase()}
            </span>
            <span className="mono" style={{
              background: 'rgba(0,0,0,0.5)', color: '#fff', padding: '4px 8px',
              fontSize: 10, borderRadius: 2, letterSpacing: '0.08em',
            }}>SKU: {sku}</span>
          </div>
          {/* Bottom format callout */}
          <div style={{
            position: 'absolute', bottom: 16, left: 16, right: 16,
            background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(4px)',
            padding: '14px 18px', borderRadius: 4, border: '1px solid rgba(0,0,0,0.05)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
          }}>
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.1em', marginBottom: 4 }}>FORMAT · MM</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>{format}</div>
            </div>
            <div style={{ height: 36, width: 1, background: 'var(--line)' }} />
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.1em', marginBottom: 4 }}>NA PALECIE</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 600 }}>{product.perPallet}<span style={{ fontSize: 11, color: 'var(--ink-4)', marginLeft: 4 }}>{product.unit}</span></div>
            </div>
            <div style={{ height: 36, width: 1, background: 'var(--line)' }} />
            <div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.1em', marginBottom: 4 }}>DOSTĘPNOŚĆ</div>
              <div style={{ fontSize: 13, fontWeight: 500, color: color.stockDays === 0 ? '#1d7a4f' : 'var(--ink)' }}>
                {color.stockDays === 0 ? '● Na stanie' : `+${color.stockDays} dni produkcja`}
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT — controls */}
        <div style={{ padding: 28, display: 'grid', gap: 28, alignContent: 'start' }}>
          {/* Step 01 — Color */}
          <div>
            <StepHead n="01" label="Kolor" hint={`${COLORS.length} dostępnych`} />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
              {COLORS.map(c => (
                <Swatch key={c.id} color={c.swatch} selected={c.id === colorId} stockDays={c.stockDays}
                  label={c.label} code={c.code} onClick={() => setColorId(c.id)} />
              ))}
            </div>
          </div>

          {/* Step 02 — Format */}
          <div>
            <StepHead n="02" label="Format" hint="MILIMETRY · D × S × W" />
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {product.formats.map((f, i) => {
                const active = i === formatIdx;
                return (
                  <button key={f} onClick={() => setFormatIdx(i)} className="mono"
                    style={{
                      padding: '12px 16px', borderRadius: 4,
                      border: active ? '1.5px solid var(--accent)' : '1px solid var(--line)',
                      background: active ? 'var(--accent-soft)' : '#fff',
                      color: active ? 'var(--ink)' : 'var(--ink-2)',
                      cursor: 'pointer', fontSize: 13, letterSpacing: '0.02em', fontWeight: active ? 600 : 400,
                    }}>{f}</button>
                );
              })}
            </div>
          </div>

          {/* Step 03 — Quantity */}
          <div>
            <StepHead n="03" label="Ilość" hint={`≈ ${totalUnits.toLocaleString('pl-PL')} ${product.unit}`} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
              <button onClick={() => setPallets(Math.max(1, pallets - 1))} style={btnStep}>−</button>
              <input type="range" min="1" max="24" value={pallets} onChange={e => setPallets(+e.target.value)}
                style={{ flex: 1, accentColor: 'var(--accent)' }} />
              <button onClick={() => setPallets(Math.min(24, pallets + 1))} style={btnStep}>+</button>
              <div style={{ minWidth: 84, textAlign: 'right' }}>
                <span style={{ fontSize: 28, fontWeight: 600, fontFamily: 'var(--font-display)', letterSpacing: '-0.02em' }}>{pallets}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', marginLeft: 4 }}>plt</span>
              </div>
            </div>
            <PalletGrid pallets={pallets} color={color.swatch} />
          </div>
        </div>
      </div>

      {/* Summary footer — full width */}
      <div style={{
        borderTop: '1px solid var(--line)', background: 'var(--bone)',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto', gap: 0, alignItems: 'stretch',
      }}>
        <SumCell label="WARTOŚĆ TOWARU" value={`${subtotal.toLocaleString('pl-PL', { maximumFractionDigits: 0 })} zł`} />
        <SumCell label="TRANSPORT" value={transport === 0 ? 'gratis' : `${transport.toLocaleString('pl-PL')} zł`} accent={transport === 0} border />
        <SumCell label="RAZEM NETTO" value={`${total.toLocaleString('pl-PL', { maximumFractionDigits: 0 })} zł`} big border />
        <div style={{ padding: 20, borderLeft: '1px solid var(--line)', background: 'var(--ink)', display: 'flex', alignItems: 'stretch' }}>
          <button className="btn btn--primary" style={{ borderRadius: 4, padding: '14px 24px', justifyContent: 'center', whiteSpace: 'nowrap' }}>
            Zamów wycenę <Arrow />
          </button>
        </div>
      </div>

      {/* Truck loading bar — full width strip at the very bottom */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 24px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.12em', whiteSpace: 'nowrap' }}>
          ZAŁADUNEK CIĘŻARÓWKI
        </span>
        <div style={{ flex: 1, height: 8, background: 'var(--bone)', borderRadius: 2, overflow: 'hidden', border: '1px solid var(--line)' }}>
          <div style={{ width: `${truckUsage}%`, height: '100%', background: 'var(--accent)', transition: 'width .25s' }} />
        </div>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>
          {truckUsage}% · ETA <strong style={{ color: 'var(--ink)' }}>{eta}</strong>
        </span>
      </div>
    </div>
  );
};

const btnStep = {
  width: 36, height: 36, borderRadius: 4, border: '1px solid var(--line)',
  background: '#fff', cursor: 'pointer', fontSize: 18, color: 'var(--ink-2)',
};

const SumCell = ({ label, value, big = false, accent = false, border = false }) => (
  <div style={{
    padding: '20px 24px',
    borderLeft: border ? '1px solid var(--line)' : 'none',
  }}>
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-4)' }}>{label}</div>
    <div style={{
      fontSize: big ? 28 : 18, fontWeight: 600,
      color: accent ? '#1d7a4f' : 'var(--ink)',
      letterSpacing: '-0.02em', marginTop: 6,
      fontFamily: 'var(--font-display)',
    }}>{value}</div>
  </div>
);

window.Configurator = Configurator;
