/* global React, ReactDOM, UNITS, NEWS, POIS, BUILDING_POLYGONS, STATUS_LABELS, fmtPrice, statusFill */
const { useState: R_useState, useEffect: R_useEffect, useMemo: R_useMemo, useRef: R_useRef } = React;

// ───────────── Shared bits ─────────────
const Brand = ({ size = 28 }) => (
  <span className="brand" style={{ fontSize: size }}>
    De From<em>berg</em>
  </span>
);

const Label = ({ children, light, steel }) => (
  <span className={`label ${light ? 'label--light' : ''} ${steel ? 'label--steel-bg' : ''}`}>{children}</span>
);

// Italic-accent helper. Tweak controls which word gets italic.
function Accent({ word, italicWord, children }) {
  // word: target word in children (string). Replaces with italic.
  if (typeof children !== 'string') return <>{children}</>;
  const target = italicWord || word;
  if (!target) return <>{children}</>;
  const idx = children.toLowerCase().indexOf(target.toLowerCase());
  if (idx < 0) return <>{children}</>;
  const before = children.slice(0, idx);
  const match = children.slice(idx, idx + target.length);
  const after = children.slice(idx + target.length);
  return <>{before}<em className="italic-accent">{match}</em>{after}</>;
}

// ───────────── Header ─────────────
function Header({ page, setPage, mobileOpen, setMobileOpen }) {
  const items = [
    { id: 'home', label: 'Home' },
    { id: 'aanbod', label: 'Aanbod' },
    { id: 'omgeving', label: 'Omgeving' },
    { id: 'nieuws', label: 'Nieuws' },
    { id: 'voorinschrijven', label: 'Voorinschrijven' },
    { id: 'contact', label: 'Contact' },
  ];
  const portalActive = page === 'portaal';
  return (
    <header className="site-header">
      <div className="site-header__inner">
        <button onClick={() => setPage('home')} aria-label="Home" style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 0, lineHeight: 1 }}>
          <Brand />
          <span style={{ fontFamily: 'var(--serif)', fontSize: 10, color: 'rgba(200,212,218,0.78)', fontWeight: 300, letterSpacing: '0.04em', marginTop: 3 }}>
            door <em style={{ fontStyle: 'italic' }}>Consent Vastgoed</em>
          </span>
        </button>
        <div className="site-header__right">
          <nav className="nav-links">
            {items.map(it => (
              <button key={it.id} className={page === it.id ? 'active' : ''} onClick={() => setPage(it.id)}>{it.label}</button>
            ))}
          </nav>
          <button
            type="button"
            className={`portal-btn${portalActive ? ' portal-btn--active' : ''}`}
            onClick={() => setPage('portaal')}
            aria-label="Kopersportaal"
          >
            <span aria-hidden="true" className="portal-btn__icon">
              <svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3.25" y="7" width="9.5" height="6.25" rx="1" />
                <path d="M5.5 7V5.25a2.5 2.5 0 0 1 5 0V7" />
              </svg>
            </span>
            <span>Kopersportaal</span>
          </button>
          <button className={`menu-toggle ${mobileOpen ? 'open' : ''}`} onClick={() => setMobileOpen(v => !v)} aria-label="Menu">
            <span /><span /><span />
          </button>
        </div>
      </div>
      {mobileOpen && (
        <div className="mobile-overlay">
          {items.map(it => (
            <button key={it.id} className={page === it.id ? 'active' : ''} onClick={() => { setPage(it.id); setMobileOpen(false); window.scrollTo(0, 0); }}>
              {page === it.id ? <em>{it.label}</em> : it.label}
            </button>
          ))}
          <button
            type="button"
            className={`portal-btn portal-btn--mobile${portalActive ? ' portal-btn--active' : ''}`}
            onClick={() => { setPage('portaal'); setMobileOpen(false); window.scrollTo(0, 0); }}
          >
            <span aria-hidden="true" className="portal-btn__icon">
              <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3.25" y="7" width="9.5" height="6.25" rx="1" />
                <path d="M5.5 7V5.25a2.5 2.5 0 0 1 5 0V7" />
              </svg>
            </span>
            <span>Kopersportaal</span>
          </button>
        </div>
      )}
    </header>
  );
}

// ───────────── Footer ─────────────
function Footer({ setPage }) {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="site-footer__grid">
          <div>
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontFamily: 'var(--serif)', fontWeight: 300, fontSize: 32, color: 'var(--bone-10)', lineHeight: 1.1 }}>
                De From<em style={{ fontStyle: 'italic', color: 'var(--bone-30)' }}>berg</em>
              </div>
              <div style={{ fontFamily: 'var(--serif)', fontSize: 12, color: 'var(--steel-30)', marginTop: 5, fontWeight: 300, letterSpacing: '0.02em' }}>door <em style={{ fontStyle: 'italic' }}>Consent Vastgoed</em></div>
            </div>
            <p style={{ color: 'var(--bone-20)', fontSize: 14, maxWidth: 360 }}>
              Frombergdwarstraat 54<br />
              6814 DZ Arnhem
            </p>
            <p style={{ color: 'var(--steel-30)', fontSize: 13, marginTop: 24, maxWidth: 360 }}>
              Een transformatieproject van Consent Vastgoed. Zestien Stads Lofts in Arnhem-Noord, geplande oplevering Q1 2028.
            </p>
          </div>
          <div>
            <h4>Navigatie</h4>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {['home', 'aanbod', 'omgeving', 'nieuws', 'voorinschrijven', 'contact'].map(p => (
                <button key={p} onClick={() => { setPage(p); window.scrollTo(0, 0); }} style={{ textAlign: 'left', fontSize: 14, color: 'var(--bone-20)' }}>
                  {p === 'home' ? 'Home' : p[0].toUpperCase() + p.slice(1)}
                </button>
              ))}
            </div>
          </div>
          <div>
            <h4>Contact</h4>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, fontSize: 14 }}>
              <span>BMV Makelaars Arnhem</span>
              <a href="mailto:defromberg@bmv.nl">defromberg@bmv.nl</a>
              <a href="tel:+31263701700">026 — 370 17 00</a>
            </div>
          </div>
        </div>
        <div className="site-footer__bottom">
          <span>© Consent Vastgoed 2026</span>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="#">Privacy</a>
            <a href="#">Cookies</a>
            <span>NL · <span style={{ opacity: 0.5 }}>EN</span></span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ───────────── Building Viewer (16 polygons, hover + click) ─────────────
function BuildingViewer({ onSelect, statusFilter, setStatusFilter, filters, setFilters, accents }) {
  const [view, setView] = R_useState('voor');
  const [hover, setHover] = R_useState(null);
  const [tipPos, setTipPos] = R_useState({ x: 0, y: 0 });
  const wrapRef = R_useRef(null);

  const polygons = BUILDING_POLYGONS[view] || [];
  const unitsById = R_useMemo(() => Object.fromEntries(UNITS.map(u => [u.id, u])), []);

  const handleMove = (e) => {
    const rect = wrapRef.current?.getBoundingClientRect();
    if (rect) setTipPos({ x: e.clientX - rect.left, y: e.clientY - rect.top });
  };

  const visibleStatuses = new Set(Object.entries(statusFilter || {}).filter(([, on]) => on).map(([k]) => k));

  return (
    <div className="building-viewer">
      <div className="bv-tabs">
        {[{id:'voor',l:'Voorzijde'},{id:'zij',l:'Zijaanzicht'},{id:'boven',l:'Bovenaanzicht'}].map(t => (
          <button key={t.id} className={view === t.id ? 'active' : ''} onClick={() => setView(t.id)}>{t.l}</button>
        ))}
      </div>
      <div className="bv-canvas" ref={wrapRef} onMouseMove={handleMove}>
        {view === 'voor' ? (
          <BuildingIllustration />
        ) : (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 12, background: 'var(--bone-10)', color: 'var(--steel-40)' }}>
            <Label>Render volgt</Label>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 28, color: 'var(--steel-50)' }}>{view === 'zij' ? 'Zijaanzicht' : 'Bovenaanzicht'}</span>
          </div>
        )}
        {view === 'voor' && (
          <svg viewBox="0 0 1000 563" preserveAspectRatio="none">
            {polygons.map(poly => {
              const u = unitsById[poly.id];
              if (!u) return null;
              const visible = visibleStatuses.has(u.status);
              const fill = visible ? statusFill(u.status) : 'rgba(255,255,255,0.05)';
              return (
                <polygon
                  key={poly.id}
                  points={poly.points}
                  fill={fill}
                  stroke="rgba(253,251,247,0.85)"
                  strokeWidth="2"
                  opacity={visible ? 1 : 0.3}
                  onMouseEnter={() => setHover(u)}
                  onMouseLeave={() => setHover(null)}
                  onClick={() => visible && onSelect(u)}
                  style={{ cursor: visible ? 'pointer' : 'not-allowed' }}
                />
              );
            })}
          </svg>
        )}
        {hover && (
          <div className="bv-tooltip" style={{ left: tipPos.x, top: tipPos.y }}>
            <strong>{hover.id}</strong>
            <div>{hover.type} · {hover.area} m²</div>
            <div style={{ marginTop: 4, color: 'var(--bone-30)' }}>{STATUS_LABELS[hover.status]}</div>
          </div>
        )}
      </div>
      <div className="bv-legend">
        {['available', 'option', 'sold'].map(s => (
          <button key={s} className="bv-legend__item" onClick={() => setStatusFilter({ ...statusFilter, [s]: !statusFilter[s] })} style={{ opacity: statusFilter[s] ? 1 : 0.4, cursor: 'pointer' }}>
            <span className={`dot dot--${s}`}></span>
            {STATUS_LABELS[s]}
          </button>
        ))}
        <span style={{ fontSize: 12, color: 'var(--steel-40)', marginTop: 4 }}>Klik een woning voor details</span>
      </div>
    </div>
  );
}

// SVG facade illustration — 3 floors, shopfront level + 2 residential floors with windows
function BuildingIllustration() {
  return (
    <svg viewBox="0 0 1000 563" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#E4EAED" />
          <stop offset="100%" stopColor="#C8D4DA" />
        </linearGradient>
        <linearGradient id="wall" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#D8CEBC" />
          <stop offset="100%" stopColor="#B3A896" />
        </linearGradient>
      </defs>
      {/* Sky */}
      <rect x="0" y="0" width="1000" height="90" fill="url(#sky)" />
      {/* Building wall */}
      <rect x="100" y="60" width="895" height="470" fill="url(#wall)" />
      {/* Cornice */}
      <rect x="100" y="60" width="895" height="14" fill="#9d927f" />
      <rect x="100" y="206" width="895" height="6" fill="#9d927f" opacity="0.5" />
      <rect x="100" y="326" width="895" height="6" fill="#9d927f" opacity="0.5" />
      {/* Plint */}
      <rect x="100" y="500" width="895" height="30" fill="#5a5246" />
      {/* Ground level shopfront windows (8 bays) */}
      {Array.from({ length: 8 }, (_, i) => {
        const x = 110 + i * 110;
        return (
          <g key={`g${i}`}>
            <rect x={x + 8} y={350} width={94} height={140} fill="#3A4550" opacity="0.55" />
            <rect x={x + 8} y={350} width={94} height={140} fill="none" stroke="#FDFBF7" strokeWidth="1.5" />
            <line x1={x + 55} y1={350} x2={x + 55} y2={490} stroke="#FDFBF7" strokeWidth="1" />
            <line x1={x + 8} y1={420} x2={x + 102} y2={420} stroke="#FDFBF7" strokeWidth="1" />
          </g>
        );
      })}
      {/* First floor windows (4 bays of 2 windows each) */}
      {Array.from({ length: 4 }, (_, i) => {
        const x = 130 + i * 220;
        return (
          <g key={`f1${i}`}>
            <rect x={x} y={235} width={80} height={75} fill="#3A4550" opacity="0.55" />
            <rect x={x} y={235} width={80} height={75} fill="none" stroke="#FDFBF7" strokeWidth="1.2" />
            <line x1={x + 40} y1={235} x2={x + 40} y2={310} stroke="#FDFBF7" strokeWidth="0.8" />
            <rect x={x + 100} y={235} width={80} height={75} fill="#3A4550" opacity="0.55" />
            <rect x={x + 100} y={235} width={80} height={75} fill="none" stroke="#FDFBF7" strokeWidth="1.2" />
            <line x1={x + 140} y1={235} x2={x + 140} y2={310} stroke="#FDFBF7" strokeWidth="0.8" />
          </g>
        );
      })}
      {/* Second floor windows */}
      {Array.from({ length: 4 }, (_, i) => {
        const x = 130 + i * 220;
        return (
          <g key={`f2${i}`}>
            <rect x={x} y={115} width={80} height={75} fill="#3A4550" opacity="0.55" />
            <rect x={x} y={115} width={80} height={75} fill="none" stroke="#FDFBF7" strokeWidth="1.2" />
            <line x1={x + 40} y1={115} x2={x + 40} y2={190} stroke="#FDFBF7" strokeWidth="0.8" />
            <rect x={x + 100} y={115} width={80} height={75} fill="#3A4550" opacity="0.55" />
            <rect x={x + 100} y={115} width={80} height={75} fill="none" stroke="#FDFBF7" strokeWidth="1.2" />
            <line x1={x + 140} y1={115} x2={x + 140} y2={190} stroke="#FDFBF7" strokeWidth="0.8" />
          </g>
        );
      })}
      {/* Subtle texture */}
      <rect x="100" y="60" width="895" height="470" fill="rgba(0,0,0,0.04)" />
    </svg>
  );
}

// ───────────── Floorplan thumb (SVG schematic per type) ─────────────
function FloorplanThumb({ unit, large }) {
  const stroke = large ? 1.5 : 1.2;
  return (
    <svg viewBox="0 0 200 150" style={{ width: '100%', height: '100%', maxHeight: large ? 520 : 200 }}>
      {/* Outer wall */}
      <rect x="20" y="20" width="160" height="110" fill="var(--bone-00)" stroke="var(--steel-50)" strokeWidth={stroke + 0.5} />
      {/* Internal walls vary by type */}
      {unit.rooms >= 3 && <line x1="100" y1="20" x2="100" y2="80" stroke="var(--steel-50)" strokeWidth={stroke} />}
      <line x1="20" y1="80" x2="180" y2="80" stroke="var(--steel-50)" strokeWidth={stroke} />
      {unit.rooms >= 4 && <line x1="100" y1="80" x2="100" y2="130" stroke="var(--steel-50)" strokeWidth={stroke} />}
      {/* Door swings */}
      <path d={`M 60 80 A 12 12 0 0 1 72 92`} fill="none" stroke="var(--steel-40)" strokeWidth="0.6" />
      {/* Garden indicator */}
      {unit.garden > 0 && (
        <g>
          <rect x="20" y="130" width="160" height="14" fill="rgba(126,168,130,0.18)" stroke="rgba(126,168,130,0.5)" strokeWidth="0.6" strokeDasharray="2 2" />
          <text x="100" y="141" textAnchor="middle" fontSize="6" fill="rgba(78,108,84,0.9)" fontFamily="var(--sans)" letterSpacing="0.1em">TUIN {unit.garden}M²</text>
        </g>
      )}
      {/* Balcony */}
      {unit.balcony > 0 && (
        <g>
          <rect x="20" y="6" width="160" height="14" fill="rgba(253,251,247,0.6)" stroke="var(--steel-30)" strokeWidth="0.6" strokeDasharray="2 2" />
          <text x="100" y="16" textAnchor="middle" fontSize="6" fill="var(--steel-50)" fontFamily="var(--sans)" letterSpacing="0.1em">BALKON {unit.balcony}M²</text>
        </g>
      )}
      {/* Room labels */}
      <text x="60" y="55" textAnchor="middle" fontSize="6" fill="var(--steel-50)" fontFamily="var(--sans)" letterSpacing="0.1em">WOONKAMER</text>
      <text x="140" y="55" textAnchor="middle" fontSize="6" fill="var(--steel-50)" fontFamily="var(--sans)" letterSpacing="0.1em">{unit.rooms >= 3 ? 'KEUKEN' : 'KEUKEN'}</text>
      <text x="60" y="108" textAnchor="middle" fontSize="6" fill="var(--steel-50)" fontFamily="var(--sans)" letterSpacing="0.1em">SLAAPK.</text>
      {unit.rooms >= 4 ? (
        <text x="140" y="108" textAnchor="middle" fontSize="6" fill="var(--steel-50)" fontFamily="var(--sans)" letterSpacing="0.1em">SLAAPK.</text>
      ) : (
        <text x="140" y="108" textAnchor="middle" fontSize="6" fill="var(--steel-50)" fontFamily="var(--sans)" letterSpacing="0.1em">BADKAMER</text>
      )}
    </svg>
  );
}

// ───────────── Unit card + modal ─────────────
function UnitCard({ unit, onClick }) {
  return (
    <div className="unit-card" onClick={onClick}>
      <div className="unit-card__media">
        <FloorplanThumb unit={unit} />
      </div>
      <div className="unit-card__body">
        <div className="unit-card__topbar">
          <span className="unit-card__num">{unit.id}</span>
          <span className={`badge badge--${unit.status}`}>{STATUS_LABELS[unit.status]}</span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--steel-50)' }}>{unit.type} · {unit.level}</div>
        <div className="unit-card__specs">
          <span><strong style={{ color: 'var(--steel-70)', fontWeight: 500 }}>{unit.area}</strong> m²</span>
          {unit.rooms > 0 && <span><strong style={{ color: 'var(--steel-70)', fontWeight: 500 }}>{unit.rooms}</strong> kamers</span>}
          {unit.garden > 0 && <span>tuin {unit.garden} m²</span>}
          {unit.balcony > 0 && <span>balkon {unit.balcony} m²</span>}
        </div>
        <div className="unit-card__price">
          <span className="unit-card__price-value">{fmtPrice(unit.price)}</span>
          <span className="link" style={{ fontSize: 10, padding: 0, border: 0 }}>Bekijken →</span>
        </div>
      </div>
    </div>
  );
}

function UnitModal({ unit, onClose }) {
  R_useEffect(() => {
    if (!unit) return;
    const handler = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', handler);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', handler); document.body.style.overflow = ''; };
  }, [unit, onClose]);

  if (!unit) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Sluiten">×</button>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', minHeight: 480 }}>
          <div style={{ background: 'var(--bone-10)', padding: 48, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRight: '1px solid var(--bone-20)' }}>
            <div style={{ width: '100%', maxWidth: 460 }}>
              <FloorplanThumb unit={unit} large />
            </div>
          </div>
          <div style={{ padding: 48, display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <Label>{unit.level}</Label>
                <h2 style={{ fontSize: 56, marginTop: 8 }}>Woning <em className="italic-accent-steel">{unit.id}</em></h2>
              </div>
              <span className={`badge badge--${unit.status}`}>{STATUS_LABELS[unit.status]}</span>
            </div>
            <p style={{ marginTop: 8 }}>{unit.description}</p>
            <div style={{ borderTop: '1px solid var(--bone-20)', paddingTop: 24, marginTop: 12 }}>
              {[
                ['Type', unit.type],
                ['Woonoppervlak', `${unit.area} m²`],
                unit.rooms > 0 && ['Aantal kamers', unit.rooms],
                unit.garden > 0 && ['Privétuin', `${unit.garden} m²`],
                unit.balcony > 0 && ['Buitenruimte', `${unit.balcony} m² balkon`],
                ['Prijsindicatie', fmtPrice(unit.price)],
              ].filter(Boolean).map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '12px 0', borderBottom: '1px solid var(--bone-20)', fontSize: 14 }}>
                  <span style={{ color: 'var(--steel-50)' }}>{k}</span>
                  <span style={{ color: 'var(--steel-70)', fontWeight: 500 }}>{v}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 16, flexWrap: 'wrap' }}>
              <button className="btn btn--primary">Direct reageren</button>
              <button className="btn btn--secondary">Aan voorkeurslijst</button>
            </div>
            <a href="#" style={{ fontSize: 12, color: 'var(--steel-50)', textDecoration: 'underline', textUnderlineOffset: 4 }}>Plattegrond als PDF downloaden</a>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Header, Footer, BuildingViewer, BuildingIllustration, UnitCard, UnitModal, FloorplanThumb, Brand, Label, Accent });
