// KSANET — Configurador v2 · Step 2 (Personalización de acabados)
const { useState, useEffect, useMemo } = React;

const ChevronP = ({ dir = 'd' }) => (
  <svg className="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"
       style={{ transform: dir === 'l' ? 'rotate(90deg)' : dir === 'd' ? 'none' : 'rotate(180deg)' }}>
    <path d="M6 9l6 6 6-6"/>
  </svg>
);

const StepperP = ({ step, onGo }) => {
  const steps = [
    { n: '01', label: 'Vivienda',       short: 'Tu vivienda' },
    { n: '02', label: 'Acabados',       short: 'Personalización' },
    { n: '03', label: 'Plan económico', short: 'Aportaciones' },
    { n: '04', label: 'Reserva',        short: 'Confirmación' },
  ];
  return (
    <nav className="cfgx-steps">
      <div className="cfgx-steps-row">
        {steps.map((s, i) => {
          const idx = i + 1;
          const status = idx < step ? 'done' : idx === step ? 'active' : 'future';
          const disabled = idx > 2;
          return (
            <button key={s.n}
                    className={`cfgx-step ${status === 'done' ? 'done' : ''} ${status === 'active' ? 'active' : ''} ${disabled && status !== 'active' ? 'disabled' : ''}`}
                    onClick={() => !disabled && onGo && onGo(idx)}>
              <span className="num">{status === 'done' ? '✓' : idx}</span>
              <span className="label">{s.label}<strong>{s.short}</strong></span>
            </button>
          );
        })}
      </div>
    </nav>
  );
};

const TopBarP = ({ promoId }) => (
  <header className="cfgx-top">
    <div className="cfgx-top-row">
      <a className="cfgx-back" href={`configurador-v2.html?id=${promoId}`}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" style={{transform:'rotate(180deg)'}}><path d="M9 6l6 6-6 6"/></svg>
        Volver a la vivienda
      </a>
      <div className="cfgx-brand-mark">KSANET <span>Configurador · acabados</span></div>
      <div className="cfgx-top-actions">
        <button className="cfgx-icon-btn">Guardar</button>
        <button className="cfgx-icon-btn">Compartir</button>
        <button className="cfgx-icon-btn">Imprimir</button>
      </div>
    </div>
  </header>
);

// Room visualization (CSS-perspective room with dynamic colors)
const RoomScene = ({ picks, room }) => {
  const cat = (id) => window.PERS_CATEGORIES.find(c => c.id === id);
  const opt = (catId, optId) => cat(catId)?.options.find(o => o.id === optId);

  const suelo = opt('suelo', picks.suelo);
  const cocina = opt('cocina', picks.cocina);
  const enc = opt('encimera', picks.encimera);
  const bano = opt('bano', picks.bano);

  // Wall is constant warm; floor + island change
  const styleVars = {
    '--floor-color': suelo?.swatch || '#c8a878',
    '--floor-pattern':
      (suelo?.pattern === 'pat-wood')
        ? 'repeating-linear-gradient(90deg, rgba(0,0,0,0.06) 0 1px, transparent 1px 12%, rgba(0,0,0,0.04) 12% 12.5%, transparent 12.5% 24%)'
        : (suelo?.pattern === 'pat-stone')
          ? 'radial-gradient(circle at 20% 30%, rgba(0,0,0,0.06) 0 14%, transparent 14%), radial-gradient(circle at 70% 60%, rgba(255,255,255,0.18) 0 10%, transparent 10%)'
          : 'none',
    '--island-color': (room === 'cocina' ? cocina?.swatch : '#2a2825') || '#2a2825',
    '--counter-color': enc?.swatch || '#d8d2c3',
    '--wall-color': (room === 'bano' ? (bano?.swatch || '#dcd4c2') : '#ece6d8'),
  };

  return (
    <div className="cfgx-pers-stage">
      <div className="cfgx-pers-meta">
        <div className="kicker">Tu vista</div>
        <div className="title">Tu <em>configuración</em></div>
        <div className="room-name">{window.PERS_ROOMS.find(r => r.id === room)?.name}</div>
      </div>

      {room === 'cocina' ? (
        <KitchenPhotoScene picks={picks} cocina={cocina} enc={enc}/>
      ) : room === 'salon' ? (
        <SalonPhotoScene picks={picks} suelo={suelo}/>
      ) : (
      <div className="cfgx-room" style={styleVars}>
        <div className="cfgx-room-header">
          <span>VIVIENDA · {window.location.search.includes('unit=') ? new URLSearchParams(location.search).get('unit') : '—'}</span>
          <span>RENDER ESQUEMÁTICO · NO VINCULANTE</span>
        </div>
        <div className="cfgx-room-canvas">
          <div className="cfgx-room-wall-back"/>
          <div className="cfgx-room-wall-left"/>
          <div className="cfgx-room-wall-right"/>
          <div className="cfgx-room-window"/>
          <div className="cfgx-room-floor"/>
          {room === 'cocina' && <div className="cfgx-room-island"/>}

          {/* Hot tags pointing to elements */}
          <div className="cfgx-room-tag" style={{ left: '8%', bottom: '12%' }}>
            <span className="tag-num">1</span> Suelo · {suelo?.name}
          </div>
          {room === 'cocina' && (
            <div className="cfgx-room-tag" style={{ left: '50%', transform: 'translateX(-50%)', bottom: '30%' }}>
              <span className="tag-num">2</span> Cocina · {cocina?.name}
            </div>
          )}
          {room !== 'cocina' && room !== 'bano' && (
            <div className="cfgx-room-tag" style={{ right: '8%', top: '20%' }}>
              <span className="tag-num">2</span> Pared · neutra cálida
            </div>
          )}
          {room === 'bano' && (
            <div className="cfgx-room-tag" style={{ left: '8%', top: '22%' }}>
              <span className="tag-num">2</span> Revestimiento · {bano?.name}
            </div>
          )}
        </div>
      </div>
      )}
    </div>
  );
};

// ─── Salón photo scene with overlays ───
const SalonPhotoScene = ({ picks, suelo }) => {
  const cat = (id) => window.PERS_CATEGORIES.find(c => c.id === id);
  const opt = (catId, optId) => cat(catId)?.options.find(o => o.id === optId);
  const puertas = opt('puertas', picks.puertas);
  return (
    <div className="cfgx-cocina-scene">
      <div className="cfgx-cocina-photo cfgx-salon-photo">
        <img src="img/salon.jpg" alt="Vista del salón-comedor"/>
        <div className="cfgx-cocina-photo-tag" style={{ left: '12%', top: '74%' }}>
          <span className="num">1</span>
          <div className="tg-body">
            <div className="tg-l">Suelo · salón y dormitorios</div>
            <div className="tg-v"><span className="dot" style={{background: suelo?.swatch}}/>{suelo?.name || '—'}</div>
          </div>
        </div>
        <div className="cfgx-cocina-photo-tag" style={{ left: '4%', top: '40%' }}>
          <span className="num">2</span>
          <div className="tg-body">
            <div className="tg-l">Puerta interior</div>
            <div className="tg-v"><span className="dot" style={{background: puertas?.swatch}}/>{puertas?.name || '—'}</div>
          </div>
        </div>
        <div className="cfgx-cocina-photo-tag" style={{ left: '46%', top: '20%' }}>
          <span className="num">3</span>
          <div className="tg-body">
            <div className="tg-l">Carpintería exterior</div>
            <div className="tg-v">Aluminio RPT · vidrio bajo emisivo</div>
          </div>
        </div>
        <div className="cfgx-cocina-photo-tag" style={{ left: '70%', top: '64%' }}>
          <span className="num">4</span>
          <div className="tg-body">
            <div className="tg-l">Terraza · pavimento exterior</div>
            <div className="tg-v">Porcelánico antideslizante C3</div>
          </div>
        </div>
      </div>

      <div className="cfgx-cocina-info cfgx-salon-info">
        <div className="cfgx-cocina-info-card">
          <div className="hd">
            <span className="num">i</span>
            <h4>Salón-comedor · características</h4>
          </div>
          <ul>
            <li>
              <div className="nm">Iluminación arquitectónica</div>
              <div className="ds">Foseado LED perimetral integrado en techo · luminaria lineal sobre isla</div>
              <div className="rf">Pre-instalación de serie</div>
            </li>
            <li>
              <div className="nm">Climatización por aerotermia</div>
              <div className="ds">Suelo radiante/refrescante zonificado · termostato wifi por estancia</div>
              <div className="rf">Calificación A · ECO</div>
            </li>
            <li>
              <div className="nm">Carpintería exterior</div>
              <div className="ds">Aluminio con rotura puente térmico · vidrio doble bajo emisivo · persianas con motor opcional</div>
              <div className="rf">Apertura corredera · sistema minimalista</div>
            </li>
          </ul>
        </div>

        <div className="cfgx-cocina-info-card">
          <div className="hd">
            <span className="num">i</span>
            <h4>Salida a terraza / jardín</h4>
          </div>
          <ul>
            <li>
              <div className="nm">Pérgola bioclimática</div>
              <div className="ds">Lamas orientables · iluminación LED integrada</div>
              <div className="rf">Opcional · plantas bajas</div>
            </li>
            <li>
              <div className="nm">Pavimento exterior</div>
              <div className="ds">Gres porcelánico antideslizante de gran formato · clase 3 · continuidad visual con interior</div>
              <div className="rf">Acabado piedra clara</div>
            </li>
            <li>
              <div className="nm">Punto de agua y luz exterior</div>
              <div className="ds">Toma de riego, punto eléctrico estanco IP44 e iluminación arquitectónica baja</div>
              <div className="rf">De serie</div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

// ─── Kitchen photo scene with overlays ───
const KitchenPhotoScene = ({ picks, cocina, enc }) => {
  const equip = window.PERS_EQUIPAMIENTO_COCINA;
  const [campana, setCampana] = useState('vedo-60');
  return (
    <div className="cfgx-cocina-scene">
      <div className="cfgx-cocina-photo">
        <img src="img/cocina.jpg" alt="Vista de la cocina"/>
        <div className="cfgx-cocina-photo-tag" style={{ left: '24%', top: '70%' }}>
          <span className="num">1</span>
          <div className="tg-body">
            <div className="tg-l">Frentes · Hönnun C100</div>
            <div className="tg-v"><span className="dot" style={{background: cocina?.swatch}}/>{cocina?.name || '—'}</div>
          </div>
        </div>
        <div className="cfgx-cocina-photo-tag" style={{ left: '34%', top: '46%' }}>
          <span className="num">2</span>
          <div className="tg-body">
            <div className="tg-l">Encimera · MY TOP</div>
            <div className="tg-v"><span className="dot" style={{background: enc?.swatch}}/>{enc?.name || '—'}</div>
          </div>
        </div>
        <div className="cfgx-cocina-photo-tag" style={{ left: '60%', top: '24%' }}>
          <span className="num">3</span>
          <div className="tg-body">
            <div className="tg-l">Equipamiento Whirlpool</div>
            <div className="tg-v">Placa · horno · microondas · campana</div>
          </div>
        </div>
        <div className="cfgx-cocina-photo-tag" style={{ left: '46%', top: '53%' }}>
          <span className="num">4</span>
          <div className="tg-body">
            <div className="tg-l">Fregadero Veravent + Stillo Hera</div>
            <div className="tg-v">Acero inox · 45×40 · monomando</div>
          </div>
        </div>
      </div>

      <div className="cfgx-cocina-info">
        <div className="cfgx-cocina-info-card">
          <div className="hd">
            <span className="num">3</span>
            <h4>{equip.electro.title}</h4>
          </div>
          <ul>
            {equip.electro.items.map(it => (
              <li key={it.ref}>
                <div className="nm">{it.name}</div>
                <div className="ds">{it.desc}</div>
                <div className="rf">REF · {it.ref}</div>
              </li>
            ))}
          </ul>
          <div className="campana-pick">
            <div className="lbl">{equip.electro.optionLabel}</div>
            <div className="opts">
              {equip.electro.options.map(o => (
                <button key={o.id}
                        className={`cmp-opt ${campana === o.id ? 'on' : ''}`}
                        onClick={() => setCampana(o.id)}>
                  <span className="nm">{o.name}</span>
                  <span className="pr">{o.price === 0 ? 'Incluido' : `+ ${o.price.toLocaleString('es-ES')} €`}</span>
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="cfgx-cocina-info-card">
          <div className="hd">
            <span className="num">4</span>
            <h4>{equip.fregaderia.title}</h4>
          </div>
          <ul>
            {equip.fregaderia.items.map(it => (
              <li key={it.ref}>
                <div className="nm">{it.name}</div>
                <div className="ds">{it.desc}</div>
                <div className="rf">REF · {it.ref}</div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
};

const RoomSwitch = ({ room, setRoom }) => (
  <div className="cfgx-room-switch">
    {window.PERS_ROOMS.map(r => (
      <button key={r.id} className={room === r.id ? 'active' : ''} onClick={() => setRoom(r.id)}>
        {r.name}
      </button>
    ))}
  </div>
);

const Presets = ({ activePreset, applyPreset }) => (
  <div className="cfgx-presets">
    {window.PERS_PRESETS.map(p => (
      <button key={p.id} className={`cfgx-preset ${activePreset === p.id ? 'active' : ''}`} onClick={() => applyPreset(p)}>
        <div className="nm">{p.name}</div>
        <div className="dl">{p.desc}</div>
        <div className="pr">{p.delta === 0 ? 'INCLUIDO' : `+ ${p.delta.toLocaleString('es-ES')} €`}</div>
      </button>
    ))}
  </div>
);

const Category = ({ cat, picks, setPick, toggleExtra, open, setOpen }) => {
  const isOpen = open;
  const isToggle = cat.type === 'toggles';

  // pick label and price delta
  let pickLabel = '';
  let delta = 0;
  if (!isToggle) {
    const sel = cat.options.find(o => o.id === picks[cat.id]);
    pickLabel = sel?.name || '—';
    delta = sel?.price || 0;
  } else {
    const count = (picks.extras || []).length;
    pickLabel = count === 0 ? 'Ninguno' : `${count} seleccionado${count === 1 ? '' : 's'}`;
    delta = (picks.extras || []).reduce((s, id) => {
      const o = cat.options.find(x => x.id === id);
      return s + (o?.price || 0);
    }, 0);
  }

  return (
    <div className={`cfgx-pers-cat ${isOpen ? 'open' : ''}`}>
      <button className="cfgx-pers-cat-head" onClick={() => setOpen(isOpen ? null : cat.id)}>
        <span className="num">{cat.num}</span>
        <span className="lbl">{cat.name}</span>
        <span className="pick">{pickLabel}</span>
        {delta > 0 && <span className="delta">+ {delta.toLocaleString('es-ES')} €</span>}
        <ChevronP/>
      </button>
      {isOpen && (
        <div className="cfgx-pers-cat-body">
          {!isToggle && (
            <div className="cfgx-opts">
              {cat.options.map(opt => (
                <button key={opt.id}
                        className={`cfgx-opt ${picks[cat.id] === opt.id ? 'selected' : ''}`}
                        onClick={() => setPick(cat.id, opt.id)}>
                  <div className={`cfgx-opt-swatch ${opt.pattern || ''}`} style={{ '--swatch': opt.swatch }}/>
                  {opt.tag && <span className="cfgx-opt-tag">{opt.tag}</span>}
                  <div className="cfgx-opt-meta">
                    <div className="cfgx-opt-name">{opt.name}</div>
                    <div className={`cfgx-opt-price ${opt.price === 0 ? 'included' : ''}`}>
                      {opt.price === 0 ? 'Incluido' : `+ ${opt.price.toLocaleString('es-ES')} €`}
                    </div>
                  </div>
                  <div className="cfgx-opt-desc">{opt.desc}</div>
                </button>
              ))}
            </div>
          )}
          {isToggle && (
            <div className="cfgx-toggle-list">
              {cat.options.map(opt => {
                const on = (picks.extras || []).includes(opt.id);
                return (
                  <div key={opt.id} className={`cfgx-toggle ${on ? 'on' : ''}`} onClick={() => toggleExtra(opt.id)}>
                    <div className="tg-info">
                      <div className="tg-name">{opt.name}</div>
                      <div className="tg-desc">{opt.desc}</div>
                    </div>
                    <div className="tg-price">+ {opt.price.toLocaleString('es-ES')} €</div>
                    <div className="tg-switch"/>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

const SummaryCard = ({ basePrice, picks, total }) => {
  const cat = (id) => window.PERS_CATEGORIES.find(c => c.id === id);
  const opt = (catId, optId) => cat(catId)?.options.find(o => o.id === optId);
  const lineFor = (catId) => {
    const o = opt(catId, picks[catId]);
    if (!o) return null;
    return (
      <div className="row" key={catId}>
        <span className="l">{cat(catId).name}</span>
        <span className="v">{o.name} <em>{o.price > 0 ? `+ ${o.price.toLocaleString('es-ES')} €` : 'incl.'}</em></span>
      </div>
    );
  };
  const extras = (picks.extras || []).map(id => {
    const o = opt('extras', id);
    return o ? (
      <div className="row" key={id}>
        <span className="l">{o.name}</span>
        <span className="v"><em>+ {o.price.toLocaleString('es-ES')} €</em></span>
      </div>
    ) : null;
  });
  return (
    <div className="cfgx-summary-card">
      <h4>Tu configuración</h4>
      <div className="row">
        <span className="l">Vivienda base</span>
        <span className="v">{basePrice.toLocaleString('es-ES')} €</span>
      </div>
      {['suelo','cocina','encimera','bano','puertas'].map(lineFor)}
      {extras}
      <div className="total">
        <span className="l">Total estimado</span>
        <span className="v">{total.toLocaleString('es-ES')} €</span>
      </div>
    </div>
  );
};

// ───── Step 2 main ─────
const PersonalizationApp = () => {
  const params = new URLSearchParams(window.location.search);
  const promoId = params.get('id') || 'edificio-victoria';
  const unitId = params.get('unit') || '';

  const data = window.getTour(promoId);
  let basePrice = 0;
  let unitMeta = null;
  try {
    const stored = JSON.parse(sessionStorage.getItem('ksa_cfg') || 'null');
    if (stored && stored.unitId === unitId) {
      basePrice = stored.basePrice;
      unitMeta = stored;
    }
  } catch (e) {}

  // Fallback: derive from tour data
  if (!basePrice && data) {
    const allUnits = data.building.floors.flatMap(f => f.units.map(u => ({ ...u, floor: f })));
    const u = allUnits.find(x => x.id === unitId) || allUnits.find(x => x.state === 'available');
    if (u) {
      const t = data.typologies.find(x => x.code === u.code);
      basePrice = t?.priceFrom || 296507;
      unitMeta = { unitId: u.id, code: u.code, typoName: t?.name, useful: t?.useful, dorms: t?.dorms, basePrice, floor: u.floor.id };
    }
  }
  if (!basePrice) basePrice = 296507;

  const defaultPicks = window.PERS_PRESETS[0].picks;
  const [picks, setPicks] = useState({ ...defaultPicks });
  const [open, setOpen] = useState('suelo');
  const [room, setRoom] = useState('salon');
  const [activePreset, setActivePreset] = useState('esencial');

  const setPick = (catId, optId) => {
    setPicks(p => ({ ...p, [catId]: optId }));
    setActivePreset(null);
  };
  const toggleExtra = (id) => {
    setPicks(p => {
      const ex = p.extras || [];
      return { ...p, extras: ex.includes(id) ? ex.filter(x => x !== id) : [...ex, id] };
    });
    setActivePreset(null);
  };
  const applyPreset = (preset) => {
    setPicks({ ...preset.picks });
    setActivePreset(preset.id);
  };

  const total = useMemo(() => {
    let t = basePrice;
    for (const c of window.PERS_CATEGORIES) {
      if (c.type === 'toggles') {
        for (const id of (picks.extras || [])) {
          const o = c.options.find(x => x.id === id);
          if (o) t += o.price;
        }
      } else {
        const o = c.options.find(x => x.id === picks[c.id]);
        if (o) t += o.price;
      }
    }
    return t;
  }, [picks, basePrice]);

  const acabadosTotal = total - basePrice;

  return (
    <div className="cfgx">
      <TopBarP promoId={promoId}/>
      <StepperP step={2} onGo={(n) => {
        if (n === 1) window.location.href = `configurador-v2.html?id=${promoId}`;
      }}/>

      <div className="cfgx-work">
        <section className="cfgx-stage">
          <div className="cfgx-stage-bar">
            <div className="cfgx-stage-title">{unitMeta?.code || 'Vivienda'} · <em>acabados</em></div>
          </div>
          <RoomScene picks={picks} room={room}/>
          <RoomSwitch room={room} setRoom={setRoom}/>
        </section>

        <aside className="cfgx-side cfgx-pers-side">
          <div className="cfgx-pers-cats-header">
            <div className="lbl">Paso 02 / 04</div>
            <h2>Acabados y <em>extras</em></h2>
          </div>
          <Presets activePreset={activePreset} applyPreset={applyPreset}/>
          <div className="cfgx-pers-cats">
            {window.PERS_CATEGORIES.map(c => (
              <Category key={c.id} cat={c} picks={picks}
                        setPick={setPick} toggleExtra={toggleExtra}
                        open={open === c.id} setOpen={setOpen}/>
            ))}
          </div>
          <SummaryCard basePrice={basePrice} picks={picks} total={total}/>
        </aside>
      </div>

      <footer className="cfgx-foot">
        <div className="cfgx-foot-row">
          <div className="cfgx-foot-block">
            <div className="l">Vivienda</div>
            <div className="v">{unitMeta?.code || '—'} <em>{unitMeta?.typoName || ''}</em></div>
          </div>
          <div className="cfgx-foot-block">
            <div className="l">Acabados elegidos</div>
            <div className="v">{acabadosTotal === 0 ? 'Memoria estándar' : `+ ${acabadosTotal.toLocaleString('es-ES')} €`}</div>
          </div>
          <div className="cfgx-foot-block price">
            <div className="l">Precio total estimado</div>
            <div className="v">{total.toLocaleString('es-ES')} €</div>
            <div className="iva">+ IVA · plan económico en el siguiente paso</div>
          </div>
          <div className="cfgx-foot-cta">
            <a className="btn btn-light" href={`configurador-v2.html?id=${promoId}`}>← Cambiar vivienda</a>
            <a className="btn btn-go" href={`contacto.html?promo=${promoId}&unit=${unitId}`}>Continuar al plan económico <span className="btn-arrow">→</span></a>
          </div>
        </div>
      </footer>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<PersonalizationApp/>);
