/* Оконный Гид — Калькулятор окон.
   Интерактивный расчёт: тип окна → створки → профиль → размеры → опции.
   Живая SVG-схема окна, цена пересчитывается мгновенно. Кнопка
   открывает форму заявки (openModal) с предзаполненным сообщением. */

const { useState: useStateC, useMemo: useMemoC } = React;

const WIN_TYPES = [
  { id: 'single', label: 'Одностворчатое', sashes: 1, w: 800, h: 1400 },
  { id: 'double', label: 'Двухстворчатое', sashes: 2, w: 1300, h: 1400 },
  { id: 'triple', label: 'Трёхстворчатое', sashes: 3, w: 2000, h: 1400 },
  { id: 'balcony', label: 'Балконный блок', sashes: 2, balcony: true, w: 1800, h: 2100 },
];

const SASH_TYPES = [
  { id: 'deaf', label: 'Глухая', premium: 0 },
  { id: 'turn', label: 'Поворотная', premium: 1600 },
  { id: 'tilt', label: 'Поворотно-откидная', premium: 2400 },
];

// Цены и названия синхронизированы с блоком «Профильные системы»
// (PROFILES в PageMid.jsx). При изменении цен править в двух местах.
const CALC_PROFILES = [
  { id: 'lite60', tier: 'Эконом', name: 'Melke Lite 60', rate: 3200 },
  { id: 'blitz', tier: 'Эконом', name: 'Rehau Blitz', rate: 3500 },
  { id: 'smart', tier: 'Комфорт', name: 'Melke Smart Ultra 65', rate: 4900 },
  { id: 'grazio', tier: 'Комфорт', name: 'Rehau Grazio', rate: 5200 },
  { id: 'evolution', tier: 'Комфорт', name: 'Melke Evolution 70', rate: 6200 },
  { id: 'intelio', tier: 'Премиум', name: 'Rehau Intelio', rate: 6750 },
  { id: 'wide', tier: 'Премиум', name: 'Melke Wide', rate: 9200 },
  { id: 'centum', tier: 'Премиум', name: 'Melke Centum', rate: 10500 },
];

const ADDONS = [
  { id: 'mount', label: 'Монтаж по ГОСТ', icon: 'gost', hint: 'демонтаж, установка, пена, герметизация' },
  { id: 'sill', label: 'Подоконник', icon: 'frame', hint: 'влагостойкий, под ширину проёма' },
  { id: 'ebb', label: 'Отлив', icon: 'ruler', hint: 'оцинкованный, с порошковой окраской' },
  { id: 'slopes', label: 'Откосы', icon: 'doc', hint: 'сэндвич-панель, тёплые' },
  { id: 'mesh', label: 'Москитная сетка', icon: 'shield', hint: 'на каждую открывающуюся створку' },
];

/* ---- SVG: одна створка с индикатором открывания ---- */
function Sash({ x, y, w, h, type, accent }) {
  const inset = 7;
  const ix = x + inset, iy = y + inset, iw = w - inset * 2, ih = h - inset * 2;
  const lines = [];
  if (type === 'turn' || type === 'tilt') {
    // поворот: вершина у правого края (петли слева)
    lines.push(`M${ix},${iy} L${ix + iw},${iy + ih / 2} L${ix},${iy + ih}`);
  }
  if (type === 'tilt') {
    // откид: вершина у нижнего края
    lines.push(`M${ix},${iy} L${ix + iw / 2},${iy + ih} L${ix + iw},${iy}`);
  }
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} fill="rgba(255,255,255,0.5)" stroke="var(--mk-graphite-700)" strokeWidth="3" />
      <rect x={ix} y={iy} width={iw} height={ih} fill="rgba(180,205,220,0.28)" stroke="var(--mk-graphite-400)" strokeWidth="1.5" />
      {lines.map((d, i) => <path key={i} d={d} fill="none" stroke={accent} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" opacity="0.9" />)}
      {type !== 'deaf' && (
        <rect x={ix + iw - 6} y={iy + ih / 2 - 16} width="4" height="32" rx="2" fill="var(--okg-terra-600)" />
      )}
    </g>
  );
}

function WindowDiagram({ type, sashes, ratio }) {
  const VB_W = 320;
  const VB_H = Math.max(180, Math.min(360, Math.round(VB_W / ratio)));
  const pad = 14;
  const accent = 'var(--okg-terra-600)';
  const t = WIN_TYPES.find((x) => x.id === type);

  let cells = [];
  if (t.balcony) {
    // дверь (узкая, во всю высоту) справа + окно слева
    const doorW = (VB_W - pad * 2) * 0.36;
    const winW = (VB_W - pad * 2) - doorW;
    const winH = (VB_H - pad * 2) * 0.62;
    cells.push({ x: pad, y: pad, w: winW, h: winH, type: sashes[0] }); // окно
    cells.push({ x: pad + winW, y: pad, w: doorW, h: VB_H - pad * 2, type: sashes[1] }); // дверь
    // подоконная глухая часть под окном
    cells.push({ x: pad, y: pad + winH, w: winW, h: (VB_H - pad * 2) - winH, type: 'deaf', filler: true });
  } else {
    const n = t.sashes;
    const cw = (VB_W - pad * 2) / n;
    for (let i = 0; i < n; i++) cells.push({ x: pad + i * cw, y: pad, w: cw, h: VB_H - pad * 2, type: sashes[i] });
  }

  return (
    <svg viewBox={`0 0 ${VB_W} ${VB_H}`} width="100%" style={{ display: 'block', borderRadius: 'var(--r-md)', background: 'linear-gradient(160deg,#eef2f4,#e3e8eb)' }}>
      <rect x="4" y="4" width={VB_W - 8} height={VB_H - 8} fill="none" stroke="var(--mk-graphite-800)" strokeWidth="5" />
      {cells.map((c, i) => <Sash key={i} x={c.x} y={c.y} w={c.w} h={c.h} type={c.type} accent={accent} />)}
    </svg>
  );
}

function Stepper({ value, min, max, step, onChange, suffix }) {
  const set = (v) => onChange(Math.max(min, Math.min(max, v)));
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 0, border: '1px solid var(--border-strong)', borderRadius: 'var(--r-sm)', overflow: 'hidden', background: '#fff' }}>
      <button type="button" onClick={() => set(value - step)} style={{ width: 44, height: 48, border: 'none', borderRight: '1px solid var(--border-hairline)', background: 'var(--surface-fill)', fontSize: 22, cursor: 'pointer', color: 'var(--text-strong)' }}>−</button>
      <input type="number" value={value} min={min} max={max} onChange={(e) => set(parseInt(e.target.value || '0', 10))}
        style={{ width: '100%', height: 48, border: 'none', textAlign: 'center', fontFamily: 'var(--font-sans)', fontSize: 17, fontWeight: 700, color: 'var(--text-strong)', outline: 'none', MozAppearance: 'textfield' }} />
      <span style={{ paddingRight: 12, fontSize: 13, color: 'var(--text-muted)' }}>{suffix}</span>
      <button type="button" onClick={() => set(value + step)} style={{ width: 44, height: 48, border: 'none', borderLeft: '1px solid var(--border-hairline)', background: 'var(--surface-fill)', fontSize: 22, cursor: 'pointer', color: 'var(--text-strong)' }}>+</button>
    </div>
  );
}

function fmt(n) { return n.toLocaleString('ru-RU'); }

function Calculator() {
  const [typeId, setTypeId] = useStateC('double');
  const t = WIN_TYPES.find((x) => x.id === typeId);
  const [sashes, setSashes] = useStateC(['turn', 'tilt']);
  const [profileId, setProfileId] = useStateC('evolution');
  const [width, setWidth] = useStateC(1300);
  const [height, setHeight] = useStateC(1400);
  const [addons, setAddons] = useStateC({ mount: true, sill: true, ebb: false, slopes: true, mesh: true });

  // при смене типа — переинициализируем створки
  const selectType = (id) => {
    const nt = WIN_TYPES.find((x) => x.id === id);
    setTypeId(id);
    setWidth(nt.w); setHeight(nt.h);
    if (nt.balcony) setSashes(['turn', 'tilt']);
    else setSashes(Array.from({ length: nt.sashes }, (_, i) => (i === 0 ? 'turn' : i === nt.sashes - 1 ? 'tilt' : 'deaf')));
  };

  const cycleSash = (i) => {
    setSashes((prev) => {
      const cur = prev[i];
      const order = ['deaf', 'turn', 'tilt'];
      const next = order[(order.indexOf(cur) + 1) % 3];
      const copy = prev.slice(); copy[i] = next; return copy;
    });
  };

  const profile = CALC_PROFILES.find((p) => p.id === profileId);
  const ratio = width / height;

  const calc = useMemoC(() => {
    const area = (width * height) / 1e6; // m²
    const profileCost = Math.round(area * profile.rate);
    const sashPremium = sashes.reduce((s, id) => s + (((SASH_TYPES.find((x) => x.id === id) || {}).premium) || 0), 0);
    const openCount = sashes.filter((s) => s !== 'deaf').length;
    const wM = width / 1000, hM = height / 1000;
    const add = {};
    if (addons.mount) add.mount = Math.round(area * 1700 + 1200);
    if (addons.sill) add.sill = Math.round(wM * 1100 + 250);
    if (addons.ebb) add.ebb = Math.round(wM * 700 + 150);
    if (addons.slopes) add.slopes = Math.round((wM + 2 * hM) * 950);
    if (addons.mesh) add.mesh = Math.max(1, openCount) * 650;
    const addTotal = Object.values(add).reduce((a, b) => a + b, 0);
    const subtotal = profileCost + sashPremium + addTotal;
    const total = Math.round(subtotal / 10) * 10;
    return { area, profileCost, sashPremium, openCount, add, addTotal, total };
  }, [width, height, profile, sashes, addons]);

  const orderMsg = `Расчёт из калькулятора: ${t.label}, профиль ${profile.name}, ${width}×${height} мм, ориентировочно ${fmt(calc.total)} ₽`;

  return (
    <section id="kalkulyator" style={{ background: 'var(--surface-subtle)' }} className="okg-section">
      <div className="okg-container">
        <SectionHead eyebrow="Калькулятор" title="Рассчитайте стоимость окна онлайн"
          sub="Соберите свою конструкцию — выберите тип, створки, профиль и размеры. Цена ориентировочная; точную сумму назовём после бесплатного замера." />

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.55fr) minmax(0,1fr)', gap: 24, alignItems: 'start' }} className="okg-calc-grid">
          {/* ЛЕВО — конструктор */}
          <div style={{ background: '#fff', border: '1px solid var(--border-hairline)', borderRadius: 'var(--r-lg)', padding: 'clamp(20px,3vw,30px)', display: 'flex', flexDirection: 'column', gap: 26 }}>
            {/* шаг 1 — тип */}
            <div>
              <CalcLabel n="1" text="Тип окна" />
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }} className="okg-calc-types">
                {WIN_TYPES.map((wt) => {
                  const on = wt.id === typeId;
                  return (
                    <button key={wt.id} type="button" onClick={() => selectType(wt.id)}
                      style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: '14px 8px', cursor: 'pointer', borderRadius: 'var(--r-md)', border: '1.5px solid ' + (on ? 'var(--okg-terra-500)' : 'var(--border-hairline)'), background: on ? 'var(--okg-terra-100)' : '#fff', transition: 'all var(--dur)' }}>
                      <MiniWin type={wt.id} active={on} />
                      <span style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.25, textAlign: 'center', color: on ? 'var(--okg-terra-700)' : 'var(--text-body)' }}>{wt.label}</span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* шаг 2 — схема + створки */}
            <div>
              <CalcLabel n="2" text="Конфигурация створок" />
              <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 22, alignItems: 'center' }} className="okg-calc-config">
                <WindowDiagram type={typeId} sashes={sashes} ratio={ratio} />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {sashes.map((s, i) => (
                    <div key={i}>
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>
                        {t.balcony ? (i === 0 ? 'Окно' : 'Дверь') : `Створка ${i + 1}`}
                      </span>
                      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                        {SASH_TYPES.map((st) => {
                          const on = s === st.id;
                          return (
                            <button key={st.id} type="button" className="okg-tap" onClick={() => { const c = sashes.slice(); c[i] = st.id; setSashes(c); }}
                              style={{ padding: '11px 13px', minHeight: 42, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', borderRadius: 'var(--r-pill)', border: '1px solid ' + (on ? 'var(--mk-graphite-800)' : 'var(--border-strong)'), background: on ? 'var(--mk-graphite-800)' : 'transparent', color: on ? '#fff' : 'var(--text-body)', transition: 'all var(--dur)' }}>
                              {st.label}{st.premium > 0 && <span style={{ opacity: 0.6, marginLeft: 4 }}>+{fmt(st.premium)}</span>}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  ))}
                  <span style={{ fontSize: 12, color: 'var(--text-faint)', lineHeight: 1.45 }}>Кликайте по типу створки — схема обновится. Глухая не открывается, поэтому дешевле.</span>
                </div>
              </div>
            </div>

            {/* шаг 3 — профиль */}
            <div>
              <CalcLabel n="3" text="Профильная система" />
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }} className="okg-calc-profiles">
                {CALC_PROFILES.map((p) => {
                  const on = p.id === profileId;
                  return (
                    <button key={p.id} type="button" onClick={() => setProfileId(p.id)}
                      style={{ textAlign: 'left', padding: '12px 14px', cursor: 'pointer', borderRadius: 'var(--r-md)', border: '1.5px solid ' + (on ? 'var(--okg-terra-500)' : 'var(--border-hairline)'), background: on ? 'var(--okg-terra-100)' : '#fff', transition: 'all var(--dur)' }}>
                      <span style={{ display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '.03em', textTransform: 'uppercase', color: 'var(--okg-terra-600)' }}>{p.tier}</span>
                      <span style={{ display: 'block', fontSize: 14, fontWeight: 700, color: 'var(--text-strong)', marginTop: 2 }}>{p.name}</span>
                      <span style={{ display: 'block', fontSize: 12.5, color: 'var(--text-muted)', marginTop: 3 }}>от {fmt(p.rate)} ₽/м²</span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* шаг 4 — размеры */}
            <div>
              <CalcLabel n="4" text="Размеры проёма" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)', display: 'block', marginBottom: 7 }}>Ширина</span>
                  <Stepper value={width} min={400} max={4000} step={50} onChange={setWidth} suffix="мм" />
                </div>
                <div>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)', display: 'block', marginBottom: 7 }}>Высота</span>
                  <Stepper value={height} min={400} max={2700} step={50} onChange={setHeight} suffix="мм" />
                </div>
              </div>
            </div>

            {/* шаг 5 — опции */}
            <div>
              <CalcLabel n="5" text="Дополнительно" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }} className="okg-calc-addons">
                {ADDONS.map((a) => {
                  const on = addons[a.id];
                  const price = calc.add[a.id];
                  return (
                    <button key={a.id} type="button" onClick={() => setAddons((p) => ({ ...p, [a.id]: !p[a.id] }))}
                      style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', cursor: 'pointer', textAlign: 'left', borderRadius: 'var(--r-md)', border: '1.5px solid ' + (on ? 'var(--okg-terra-500)' : 'var(--border-hairline)'), background: on ? 'var(--okg-terra-100)' : '#fff', transition: 'all var(--dur)' }}>
                      <span style={{ width: 24, height: 24, flex: 'none', borderRadius: 6, border: '1.5px solid ' + (on ? 'var(--okg-terra-600)' : 'var(--border-strong)'), background: on ? 'var(--okg-terra-600)' : '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
                        {on && <Icon name="check" size={15} stroke={3} />}
                      </span>
                      <span style={{ flex: 1 }}>
                        <span style={{ display: 'block', fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{a.label}</span>
                        <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-faint)', lineHeight: 1.3, marginTop: 1 }}>{a.hint}</span>
                      </span>
                      {on && price != null && <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--okg-terra-700)', whiteSpace: 'nowrap' }}>+{fmt(price)}</span>}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* ПРАВО — итог (sticky) */}
          <div style={{ position: 'sticky', top: 'calc(var(--header-h) + 16px)', display: 'flex', flexDirection: 'column', gap: 16, background: 'var(--surface-ink)', borderRadius: 'var(--r-lg)', padding: 'clamp(22px,3vw,28px)' }}>
            <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#fff' }}>Ваша конструкция</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, paddingBottom: 16, borderBottom: '1px solid var(--border-on-dark)' }}>
              <Row k={t.label} v={`${width}×${height} мм`} />
              <Row k="Площадь" v={`${calc.area.toFixed(2)} м²`} />
              <Row k={profile.name} v={`${fmt(calc.profileCost)} ₽`} />
              {calc.sashPremium > 0 && <Row k={`Открывание · ${calc.openCount} ств.`} v={`${fmt(calc.sashPremium)} ₽`} />}
              {ADDONS.filter((a) => addons[a.id]).map((a) => <Row key={a.id} k={a.label} v={`${fmt(calc.add[a.id])} ₽`} />)}
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 14, color: 'rgba(255,255,255,.7)' }}>Итого, ориентировочно</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: -6 }}>
              <span style={{ fontSize: 'clamp(34px,5vw,44px)', fontWeight: 800, color: '#fff', letterSpacing: '-.02em', lineHeight: 1 }}>{fmt(calc.total)}</span>
              <span style={{ fontSize: 22, fontWeight: 700, color: 'rgba(255,255,255,.8)' }}>₽</span>
            </div>
            <Button size="lg" fullWidth iconRight="arrowR" onClick={() => openModal('callback', orderMsg)}>Заказать по этой цене</Button>
            <button type="button" onClick={() => openModal('measure', orderMsg)} style={{ background: 'none', border: 'none', color: '#fff', fontSize: 14, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7, opacity: 0.85, minHeight: 44, padding: '10px 12px' }}>
              <Icon name="ruler" size={17} /> Вызвать бесплатный замер
            </button>
            <span style={{ fontSize: 11.5, color: 'rgba(255,255,255,.5)', lineHeight: 1.45, textAlign: 'center' }}>Расчёт предварительный и не является публичной офертой. Точную стоимость подтвердит замерщик.</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function CalcLabel({ n, text }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
      <span style={{ width: 26, height: 26, flex: 'none', borderRadius: '50%', background: 'var(--mk-graphite-800)', color: '#fff', fontSize: 13, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{n}</span>
      <span style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-strong)' }}>{text}</span>
    </div>
  );
}

function Row({ k, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 14 }}>
      <span style={{ color: 'rgba(255,255,255,.66)' }}>{k}</span>
      <span style={{ color: '#fff', fontWeight: 600, textAlign: 'right' }}>{v}</span>
    </div>
  );
}

/* мини-иконка типа окна для кнопок выбора */
function MiniWin({ type, active }) {
  const stroke = active ? 'var(--okg-terra-600)' : 'var(--mk-graphite-600)';
  const col = 'var(--mk-graphite-800)';
  return (
    <svg width="46" height="40" viewBox="0 0 46 40" fill="none">
      <rect x="3" y="2" width="40" height="36" stroke={col} strokeWidth="2.5" />
      {type === 'single' && <line x1="23" y1="4" x2="23" y2="36" stroke={stroke} strokeWidth="1.5" opacity="0" />}
      {type === 'double' && <line x1="23" y1="3" x2="23" y2="37" stroke={col} strokeWidth="2" />}
      {type === 'triple' && <g stroke={col} strokeWidth="2"><line x1="16.3" y1="3" x2="16.3" y2="37" /><line x1="29.6" y1="3" x2="29.6" y2="37" /></g>}
      {type === 'balcony' && <g stroke={col} strokeWidth="2"><line x1="27" y1="3" x2="27" y2="37" /><line x1="3" y1="24" x2="27" y2="24" /></g>}
      {(type === 'single' || type === 'double' || type === 'triple') && <path d="M7 6 L19 20 L7 34" stroke={stroke} strokeWidth="1.6" fill="none" />}
      {type === 'balcony' && <path d="M40 6 L31 20 L40 34" stroke={stroke} strokeWidth="1.6" fill="none" />}
    </svg>
  );
}

Object.assign(window, { Calculator });
