// Live mock of the garage configurator product itself.
// Embedded in the demo section so prospects can play with it.

const COLORS_RAL = [
  { id: 'graphite', name: 'Grafit', hex: '#3a3a3c', ral: 'RAL 7016' },
  { id: 'antracyt', name: 'Antracyt', hex: '#4b5159', ral: 'RAL 7024' },
  { id: 'brown',    name: 'Brąz',    hex: '#5a3a2b', ral: 'RAL 8017' },
  { id: 'red',      name: 'Czerwień', hex: '#9b2a2a', ral: 'RAL 3009' },
  { id: 'green',    name: 'Zieleń',   hex: '#2f4a36', ral: 'RAL 6005' },
  { id: 'cream',    name: 'Kremowy', hex: '#d9cfa8', ral: 'RAL 1015' },
];

const ROOF_TYPES = [
  { id: 'flat', name: 'Płaski' },
  { id: 'pent', name: 'Spadzisty' },
  { id: 'gable', name: 'Dwuspadowy' },
];

const DOOR_TYPES = [
  { id: 'roller', name: 'Roleta' },
  { id: 'tilt', name: 'Uchylna' },
  { id: 'sectional', name: 'Segmentowa' },
];

// Live pricing — rough but realistic-feeling
function calcPrice(cfg) {
  const base = 1850; // PLN per m² of footprint baseline
  const area = cfg.width * cfg.length;
  let total = base * area;
  total += cfg.height > 2.4 ? (cfg.height - 2.4) * 1200 : 0;
  if (cfg.roof === 'pent') total += 800;
  if (cfg.roof === 'gable') total += 2200;
  if (cfg.door === 'sectional') total += 1900;
  if (cfg.door === 'roller') total += 1200;
  total += cfg.windows * 480;
  total += cfg.insulated ? area * 320 : 0;
  return Math.round(total / 10) * 10;
}

function GarageVisual({ cfg, accent }) {
  // Schematic front + side elevation, scales with dimensions
  const w = cfg.width, l = cfg.length, h = cfg.height;
  const colorHex = COLORS_RAL.find(c => c.id === cfg.color)?.hex || '#3a3a3c';

  // Front view: width × height. Door takes 60% of width.
  const SCALE = 38;
  const W = w * SCALE, H = h * SCALE;
  const doorW = W * 0.62, doorH = H * 0.78;
  const doorX = (W - doorW) / 2;
  const doorY = H - doorH;

  // Roof
  const roofH = cfg.roof === 'flat' ? 6 : cfg.roof === 'pent' ? 16 : 28;

  // Side view (compact)
  const Ws = l * SCALE * 0.65, Hs = h * SCALE;
  const sideRoofH = cfg.roof === 'flat' ? 4 : cfg.roof === 'pent' ? 12 : 22;

  return (
    <svg viewBox={`0 0 ${W + 60 + Ws} ${H + roofH + 60}`}
         style={{ width: '100%', height: '100%', maxHeight: 360 }}
         preserveAspectRatio="xMidYMax meet">
      {/* ground line */}
      <line x1="0" y1={H + roofH + 32} x2={W + 60 + Ws} y2={H + roofH + 32}
            stroke="#d4d3ce" strokeWidth="0.8" strokeDasharray="3 4" />

      {/* FRONT VIEW */}
      <g transform={`translate(10, ${30})`}>
        {/* roof */}
        {cfg.roof === 'gable' ? (
          <polygon points={`-4,${roofH} ${W/2},0 ${W+4},${roofH}`}
                   fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        ) : cfg.roof === 'pent' ? (
          <polygon points={`-2,${roofH} ${W+2},2 ${W+2},${roofH}`}
                   fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        ) : (
          <rect x="-2" y="0" width={W+4} height={roofH}
                fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        )}
        {/* body */}
        <rect x="0" y={roofH} width={W} height={H}
              fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        {/* corrugation lines (vertical ribs) */}
        {Array.from({ length: Math.floor(W / 8) }).map((_, i) => (
          <line key={i} x1={i*8 + 4} y1={roofH+2} x2={i*8 + 4} y2={roofH+H-2}
                stroke="rgba(0,0,0,0.18)" strokeWidth="0.4" />
        ))}
        {/* door */}
        <rect x={doorX} y={roofH + doorY} width={doorW} height={doorH}
              fill="rgba(255,255,255,0.15)" stroke="#0a0a0a" strokeWidth="0.8" />
        {cfg.door === 'sectional' && Array.from({ length: 5 }).map((_, i) => (
          <line key={i} x1={doorX+2} y1={roofH + doorY + (i+1)*doorH/5}
                x2={doorX+doorW-2} y2={roofH + doorY + (i+1)*doorH/5}
                stroke="rgba(255,255,255,0.4)" strokeWidth="0.6" />
        ))}
        {cfg.door === 'roller' && Array.from({ length: 12 }).map((_, i) => (
          <line key={i} x1={doorX+2} y1={roofH + doorY + (i+1)*doorH/12}
                x2={doorX+doorW-2} y2={roofH + doorY + (i+1)*doorH/12}
                stroke="rgba(255,255,255,0.3)" strokeWidth="0.4" />
        ))}
        {/* windows */}
        {cfg.windows >= 1 && (
          <rect x={6} y={roofH + 8} width={doorX - 12} height={Math.min(18, H*0.18)}
                fill="rgba(180,210,230,0.65)" stroke="#0a0a0a" strokeWidth="0.6" />
        )}
        {cfg.windows >= 2 && (
          <rect x={doorX + doorW + 6} y={roofH + 8} width={W - doorX - doorW - 12} height={Math.min(18, H*0.18)}
                fill="rgba(180,210,230,0.65)" stroke="#0a0a0a" strokeWidth="0.6" />
        )}
        {/* labels */}
        <text x={W/2} y={H + roofH + 18} textAnchor="middle"
              fontFamily="Geist Mono" fontSize="9" fill="#6b6b66">
          {w.toFixed(1)} m
        </text>
        <text x={-8} y={roofH + H/2} textAnchor="end"
              fontFamily="Geist Mono" fontSize="9" fill="#6b6b66"
              transform={`rotate(-90, -8, ${roofH + H/2})`}>
          {h.toFixed(1)} m
        </text>
      </g>

      {/* SIDE VIEW */}
      <g transform={`translate(${W + 50}, 30)`}>
        {cfg.roof === 'gable' ? (
          <polygon points={`0,${sideRoofH + 2} ${Ws/2},0 ${Ws},${sideRoofH+2}`}
                   fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        ) : cfg.roof === 'pent' ? (
          <polygon points={`0,${sideRoofH} ${Ws},2 ${Ws},${sideRoofH}`}
                   fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        ) : (
          <rect x="0" y="0" width={Ws} height={sideRoofH}
                fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        )}
        <rect x="0" y={sideRoofH} width={Ws} height={Hs}
              fill={colorHex} stroke="#1a1a1a" strokeWidth="0.6" />
        {Array.from({ length: Math.floor(Ws / 8) }).map((_, i) => (
          <line key={i} x1={i*8 + 4} y1={sideRoofH+2} x2={i*8 + 4} y2={sideRoofH+Hs-2}
                stroke="rgba(0,0,0,0.18)" strokeWidth="0.4" />
        ))}
        <text x={Ws/2} y={Hs + sideRoofH + 18} textAnchor="middle"
              fontFamily="Geist Mono" fontSize="9" fill="#6b6b66">
          {l.toFixed(1)} m
        </text>
      </g>

      {/* view labels */}
      <text x={10} y={20} fontFamily="Geist Mono" fontSize="8.5" fill="#6b6b66"
            letterSpacing="0.04em">FRONT</text>
      <text x={W + 50} y={20} fontFamily="Geist Mono" fontSize="8.5" fill="#6b6b66"
            letterSpacing="0.04em">BOK</text>
    </svg>
  );
}

function ConfiguratorDemo({ accent = 'var(--accent)' }) {
  const [cfg, setCfg] = React.useState({
    width: 4.0,
    length: 6.0,
    height: 2.4,
    color: 'graphite',
    roof: 'pent',
    door: 'sectional',
    windows: 1,
    insulated: false,
  });
  const set = (key, val) => setCfg(c => ({ ...c, [key]: val }));
  const price = calcPrice(cfg);
  const area = (cfg.width * cfg.length).toFixed(1);

  const colorHex = COLORS_RAL.find(c => c.id === cfg.color)?.hex || '#3a3a3c';

  return (
    <div style={demoStyles.shell}>
      {/* Top bar */}
      <div style={demoStyles.topBar}>
        <div style={demoStyles.brandRow}>
          <div style={demoStyles.logoMark}>
            <span style={{ background: 'var(--accent)' }} />
            <span style={{ background: 'var(--accent)', opacity: 0.5 }} />
          </div>
          <span style={{ fontWeight: 600, letterSpacing: '-0.01em' }}>Twoja Firma · Konfigurator</span>
        </div>
        <div style={demoStyles.steps}>
          <span style={demoStyles.stepActive}>1. Wymiary</span>
          <span style={demoStyles.stepActive}>2. Konstrukcja</span>
          <span style={demoStyles.stepActive}>3. Wykończenie</span>
          <span style={demoStyles.step}>4. Kontakt</span>
        </div>
      </div>

      <div style={demoStyles.body}>
        {/* LEFT: controls */}
        <div style={demoStyles.controls}>
          <div style={demoStyles.section}>
            <div style={demoStyles.sectionHd}>Wymiary</div>

            <RangeRow label="Szerokość" value={cfg.width} unit="m"
                      min={2.5} max={8} step={0.5}
                      onChange={v => set('width', v)} />
            <RangeRow label="Długość" value={cfg.length} unit="m"
                      min={3} max={12} step={0.5}
                      onChange={v => set('length', v)} />
            <RangeRow label="Wysokość" value={cfg.height} unit="m"
                      min={2.0} max={3.5} step={0.1}
                      onChange={v => set('height', v)} />
          </div>

          <div style={demoStyles.section}>
            <div style={demoStyles.sectionHd}>Dach</div>
            <SegRow options={ROOF_TYPES} value={cfg.roof}
                    onChange={v => set('roof', v)} />
          </div>

          <div style={demoStyles.section}>
            <div style={demoStyles.sectionHd}>Brama</div>
            <SegRow options={DOOR_TYPES} value={cfg.door}
                    onChange={v => set('door', v)} />
          </div>

          <div style={demoStyles.section}>
            <div style={demoStyles.sectionHd}>Okna</div>
            <SegRow options={[{id:0,name:'Brak'},{id:1,name:'1 okno'},{id:2,name:'2 okna'}]}
                    value={cfg.windows} onChange={v => set('windows', v)} />
          </div>

          <div style={demoStyles.section}>
            <div style={demoStyles.sectionHd}>Kolor</div>
            <div style={demoStyles.colorGrid}>
              {COLORS_RAL.map(c => (
                <button key={c.id} type="button"
                        onClick={() => set('color', c.id)}
                        title={`${c.name} · ${c.ral}`}
                        style={{
                          ...demoStyles.colorChip,
                          background: c.hex,
                          outline: cfg.color === c.id
                            ? `2px solid var(--accent)`
                            : '1px solid rgba(0,0,0,0.1)',
                          outlineOffset: cfg.color === c.id ? 2 : 0,
                        }}>
                </button>
              ))}
            </div>
            <div style={demoStyles.colorLabel} className="mono">
              {COLORS_RAL.find(c => c.id === cfg.color)?.name} ·{' '}
              {COLORS_RAL.find(c => c.id === cfg.color)?.ral}
            </div>
          </div>

          <label style={demoStyles.checkRow}>
            <input type="checkbox"
                   checked={cfg.insulated}
                   onChange={e => set('insulated', e.target.checked)} />
            <span><b>Ocieplenie</b> — pianka PUR 40 mm</span>
          </label>
        </div>

        {/* RIGHT: visual + summary */}
        <div style={demoStyles.viewer}>
          <div style={demoStyles.canvas}>
            <GarageVisual cfg={cfg} accent={accent} />
          </div>

          <div style={demoStyles.summary}>
            <div style={demoStyles.summaryGrid}>
              <SummaryStat label="Powierzchnia" value={`${area} m²`} />
              <SummaryStat label="Kubatura" value={`${(cfg.width*cfg.length*cfg.height).toFixed(1)} m³`} />
              <SummaryStat label="Czas realizacji" value="14–21 dni" />
              <SummaryStat label="Gwarancja" value="10 lat" />
            </div>

            <div style={demoStyles.priceCard}>
              <div>
                <div style={demoStyles.priceLabel} className="mono">CENA NETTO</div>
                <div style={demoStyles.priceValue}>
                  {price.toLocaleString('pl-PL')} <span style={{ fontSize: 16, fontWeight: 500, color: 'var(--ink-dim)' }}>zł</span>
                </div>
                <div style={demoStyles.priceSub}>
                  brutto: {Math.round(price * 1.23).toLocaleString('pl-PL')} zł · transport gratis
                </div>
              </div>
              <button style={demoStyles.priceCta}>
                Zamów →
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function RangeRow({ label, value, unit, min, max, step, onChange }) {
  return (
    <div style={demoStyles.rangeRow}>
      <div style={demoStyles.rangeHead}>
        <span style={demoStyles.rangeLabel}>{label}</span>
        <span style={demoStyles.rangeVal} className="mono">
          {value.toFixed(step < 1 ? 1 : 0)} {unit}
        </span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value}
             onChange={e => onChange(Number(e.target.value))}
             style={demoStyles.rangeInput} />
      <div style={demoStyles.rangeTicks} className="mono">
        <span>{min}</span><span>{max}</span>
      </div>
    </div>
  );
}

function SegRow({ options, value, onChange }) {
  return (
    <div style={demoStyles.seg}>
      {options.map(opt => (
        <button key={opt.id} type="button"
                onClick={() => onChange(opt.id)}
                style={{
                  ...demoStyles.segBtn,
                  ...(value === opt.id ? demoStyles.segBtnActive : {}),
                }}>
          {opt.name}
        </button>
      ))}
    </div>
  );
}

function SummaryStat({ label, value }) {
  return (
    <div style={demoStyles.stat}>
      <div style={demoStyles.statLabel} className="mono">{label}</div>
      <div style={demoStyles.statValue}>{value}</div>
    </div>
  );
}

const demoStyles = {
  shell: {
    background: '#fff',
    border: '1px solid var(--border)',
    borderRadius: 14,
    overflow: 'hidden',
    boxShadow: '0 30px 60px -30px rgba(0,0,0,0.12), 0 8px 20px -10px rgba(0,0,0,0.06)',
  },
  topBar: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '14px 20px',
    borderBottom: '1px solid var(--border)',
    background: 'var(--bg-soft)',
    fontSize: 13,
    gap: 16,
    flexWrap: 'wrap',
  },
  brandRow: { display: 'flex', alignItems: 'center', gap: 10, whiteSpace: 'nowrap' },
  logoMark: { display: 'flex', gap: 2 },
  steps: { display: 'flex', gap: 14, fontSize: 12, flexWrap: 'wrap' },
  step: { color: 'var(--ink-dim)', fontFamily: "'Geist Mono', monospace", whiteSpace: 'nowrap' },
  stepActive: { color: 'var(--ink)', fontFamily: "'Geist Mono', monospace", fontWeight: 500, whiteSpace: 'nowrap' },

  body: { display: 'grid', gridTemplateColumns: '320px 1fr' },

  controls: {
    padding: '20px 22px',
    borderRight: '1px solid var(--border)',
    display: 'flex', flexDirection: 'column', gap: 22,
    background: '#fff',
  },
  section: { display: 'flex', flexDirection: 'column', gap: 10 },
  sectionHd: {
    fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
    color: 'var(--ink-dim)', fontFamily: "'Geist Mono', monospace",
    fontWeight: 500,
  },

  rangeRow: { display: 'flex', flexDirection: 'column', gap: 6 },
  rangeHead: { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' },
  rangeLabel: { fontSize: 13, color: 'var(--ink-mid)' },
  rangeVal: { fontSize: 13, fontWeight: 500, color: 'var(--ink)', whiteSpace: 'nowrap' },
  rangeInput: {
    width: '100%', accentColor: 'var(--accent)',
    height: 4,
  },
  rangeTicks: {
    display: 'flex', justifyContent: 'space-between',
    fontSize: 10, color: 'var(--ink-dim)',
  },

  seg: {
    display: 'flex', gap: 4, background: 'var(--bg-soft)',
    padding: 3, borderRadius: 9, border: '1px solid var(--border)',
  },
  segBtn: {
    flex: 1, padding: '7px 8px', fontSize: 12.5,
    border: 'none', background: 'transparent',
    cursor: 'pointer', borderRadius: 6,
    color: 'var(--ink-dim)', fontFamily: 'inherit',
    transition: 'all .12s',
  },
  segBtnActive: {
    background: '#fff', color: 'var(--ink)', fontWeight: 500,
    boxShadow: '0 1px 2px rgba(0,0,0,0.06), 0 0 0 1px var(--border)',
  },

  colorGrid: { display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 },
  colorChip: {
    height: 32, width: '100%',
    borderRadius: 6, border: 'none', cursor: 'pointer',
    padding: 0,
  },
  colorLabel: { fontSize: 11, color: 'var(--ink-dim)', marginTop: 4 },

  checkRow: {
    display: 'flex', gap: 9, alignItems: 'center',
    fontSize: 13, color: 'var(--ink-mid)', cursor: 'pointer',
    padding: '10px 12px', background: 'var(--bg-soft)',
    border: '1px solid var(--border)', borderRadius: 8,
  },

  viewer: {
    display: 'flex', flexDirection: 'column',
    background: 'linear-gradient(180deg, #fcfcfa 0%, #f3f2ed 100%)',
  },
  canvas: {
    flex: 1, minHeight: 320,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: '24px 28px',
  },
  summary: {
    padding: '18px 22px 22px',
    borderTop: '1px solid var(--border)',
    background: '#fff',
    display: 'flex', flexDirection: 'column', gap: 14,
  },
  summaryGrid: {
    display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14,
  },
  stat: { display: 'flex', flexDirection: 'column', gap: 2 },
  statLabel: {
    fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase',
    color: 'var(--ink-dim)',
  },
  statValue: { fontSize: 15, fontWeight: 500, color: 'var(--ink)' },

  priceCard: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '14px 16px',
    background: 'var(--bg-warm)',
    border: '1px solid var(--border)',
    borderRadius: 10,
  },
  priceLabel: {
    fontSize: 10, letterSpacing: '0.08em',
    color: 'var(--ink-dim)', marginBottom: 2,
  },
  priceValue: {
    fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em',
    fontVariantNumeric: 'tabular-nums',
    whiteSpace: 'nowrap',
  },
  priceSub: {
    fontSize: 11, color: 'var(--ink-dim)', marginTop: 2,
    fontFamily: "'Geist Mono', monospace",
  },
  priceCta: {
    background: 'var(--accent)', color: '#fff', border: 'none',
    padding: '12px 22px', borderRadius: 8, fontWeight: 500, fontSize: 14,
    cursor: 'pointer', fontFamily: 'inherit',
    whiteSpace: 'nowrap', flexShrink: 0,
    boxShadow: '0 4px 12px -4px color-mix(in oklab, var(--accent) 50%, transparent)',
  },
};

Object.assign(window, { ConfiguratorDemo, GarageVisual, calcPrice, COLORS_RAL });
