// Maison 57 — Grundriss-Layer (v4 Herzstück).
// Stilisierte, schematische SVG-Geschosspläne aus dem Datenbestand: nur Kontur,
// Wohnungstrennungen, Freiflächen als feine Schraffur, Nordpfeil. Keine Vermaßung,
// keine Möblierung. Flächen maßstäblich zur Wohnfläche. Status-Färbung + Hover-Sync.
// WICHTIG: bewusst schematisch, keine 1:1-Kopie der Architektenpläne (Flächen "ca.").
const GReact = window.React;

const STATUS_LABEL = { verfuegbar: 'verfügbar', reserviert: 'reserviert', verkauft: 'verkauft' };
const FLOORS_DESC = ['DG', '2.OG', '1.OG', 'EG']; // oben nach unten
const FLOOR_CONTENT = {
  'EG':   { label: 'Erdgeschoss', text: 'Eigengärten und Flexizonen' },
  '1.OG': { label: '1. Obergeschoss', text: 'Balkone in die Baumkronen' },
  '2.OG': { label: '2. Obergeschoss', text: 'Balkone, mehr Licht, mehr Weite' },
  'DG':   { label: 'Dachgeschoss', text: 'Terrassen mit Blick über Wien' },
};

// Ein Geschoss-Plan (Draufsicht) für ein Haus: Wohnungen als flächenproportionale
// Zellen nebeneinander, Freifläche als schraffierter Streifen zur Außenkante.
function FloorPlanSVG({ units, hot, onHover, onSelect, height = 200, idBase = 'fp' }) {
  const total = units.reduce((s, u) => s + (u.flaecheNum || 60), 0) || 1;
  const W = 760, H = 400, pad = 10;
  const innerW = W - pad * 2;
  let x = pad;
  const wohnH = H * 0.62, freiH = H * 0.24, gap = 4;
  const top = pad, freiTop = top + wohnH + gap;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ height: 'auto', display: 'block' }} role="img" aria-label="Geschossplan">
      <defs>
        <pattern id={idBase + '-frei'} width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="7" stroke="var(--sandstein)" strokeWidth="1" />
        </pattern>
        <pattern id={idBase + '-sold'} width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="8" stroke="var(--sandstein)" strokeWidth="1.5" />
        </pattern>
      </defs>
      {/* Nordpfeil */}
      <g transform={`translate(${W - 34}, 26)`}>
        <line x1="0" y1="10" x2="0" y2="-10" stroke="var(--umbra-60)" strokeWidth="1" />
        <path d="M0,-12 L3,-5 L-3,-5 Z" fill="var(--umbra-60)" />
        <text x="0" y="24" textAnchor="middle" fontFamily="var(--font-text)" fontSize="11" fill="var(--umbra-60)">N</text>
      </g>
      {units.map((u) => {
        const w = Math.max(48, (u.flaecheNum || 60) / total * innerW);
        const cx = x; x += w;
        const isHot = hot && hot.id === u.id;
        const sold = u.status === 'verkauft';
        const reserved = u.status === 'reserviert';
        const fill = isHot ? 'rgba(47,70,54,0.12)' : reserved ? 'var(--sandstein-40)' : 'var(--warmweiss)';
        const stroke = isHot ? 'var(--waldgruen)' : 'var(--umbra)';
        const sw = isHot ? 2 : 1;
        return (
          <g key={u.id}
            onMouseEnter={() => onHover && onHover(u)} onMouseLeave={() => onHover && onHover(null)}
            onClick={() => onSelect && onSelect(u)} style={{ cursor: onSelect ? 'pointer' : 'default' }}>
            {/* Wohnung */}
            <rect x={cx + 1} y={top} width={w - 2} height={wohnH} fill={fill} stroke={stroke} strokeWidth={sw} />
            {sold && <rect x={cx + 1} y={top} width={w - 2} height={wohnH} fill={`url(#${idBase}-sold)`} opacity="0.7" />}
            {/* Freifläche */}
            <rect x={cx + 1} y={freiTop} width={w - 2} height={freiH} fill={isHot ? 'rgba(47,70,54,0.12)' : `url(#${idBase}-frei)`} stroke={isHot ? 'var(--waldgruen)' : 'var(--sandstein)'} strokeWidth={sw} />
            {/* Top-Nummer */}
            <text x={cx + w / 2} y={top + wohnH / 2 - 4} textAnchor="middle" fontFamily="var(--font-display)" fontSize="19"
              fill={isHot ? 'var(--waldgruen)' : sold ? 'var(--sandstein)' : 'var(--umbra)'}
              style={{ textDecoration: sold ? 'line-through' : 'none' }}>{u.top}</text>
            <text x={cx + w / 2} y={top + wohnH / 2 + 16} textAnchor="middle" fontFamily="var(--font-text)" fontSize="11"
              fill={isHot ? 'var(--waldgruen)' : 'var(--umbra-60)'} style={{ fontVariantNumeric: 'tabular-nums' }}>{u.flaeche} m²</text>
            <text x={cx + w / 2} y={freiTop + freiH / 2 + 4} textAnchor="middle" fontFamily="var(--font-text)" fontSize="10" fill="var(--umbra-60)">{u.freiflaeche}</text>
          </g>
        );
      })}
    </svg>
  );
}

// Geschossstapel-Icon beider Häuser, hangbedingt um ein Geschoss versetzt
// (Haus 5 sitzt höher). Aktives Geschoss gefüllt. Wie die Legende auf den Planblättern.
function StackIcon({ activeFloor, activeHaus, width = 128 }) {
  const rows = ['DG', '2.OG', '1.OG', 'EG'];
  const cellH = 15, cellW = 44, gap = 3, offset = cellH + gap; // Haus 5 um eine Ebene höher
  const H = rows.length * (cellH + gap) + offset;
  const W = cellW * 2 + 16;
  const cell = (haus, fl, i) => {
    const active = activeFloor === fl && (activeHaus == null || String(activeHaus) === String(haus));
    const x = haus === 7 ? 0 : cellW + 16;
    const y = (haus === 7 ? offset : 0) + i * (cellH + gap);
    return (
      <g key={haus + fl}>
        <rect x={x} y={y} width={cellW} height={cellH} fill={active ? 'var(--waldgruen)' : 'var(--warmweiss)'} stroke={active ? 'var(--waldgruen)' : 'var(--sandstein)'} strokeWidth="1" />
        <text x={x + cellW / 2} y={y + cellH / 2 + 3.5} textAnchor="middle" fontFamily="var(--font-text)" fontSize="8" fill={active ? 'var(--warmweiss)' : 'var(--umbra-60)'}>{fl}</text>
      </g>
    );
  };
  return (
    <svg viewBox={`0 0 ${W} ${H + 16}`} width={width} style={{ height: 'auto', display: 'block' }} role="img" aria-label="Geschossstapel">
      <text x={cellW / 2} y={H + 12} textAnchor="middle" fontFamily="var(--font-text)" fontSize="9" fill="var(--umbra-60)">Haus 7</text>
      <text x={cellW + 16 + cellW / 2} y={H + 12} textAnchor="middle" fontFamily="var(--font-text)" fontSize="9" fill="var(--umbra-60)">Haus 5</text>
      {rows.map((fl, i) => cell(7, fl, i))}
      {rows.map((fl, i) => cell(5, fl, i))}
      {/* Erdlinie / Hang */}
      <line x1="0" y1={H} x2={cellW} y2={H} stroke="var(--umbra)" strokeWidth="2" />
      <line x1={cellW + 16} y1={H - offset} x2={W} y2={H - offset} stroke="var(--umbra)" strokeWidth="2" />
    </svg>
  );
}

Object.assign(window, { FloorPlanSVG, StackIcon, M57_FLOORS_DESC: FLOORS_DESC, M57_FLOOR_CONTENT: FLOOR_CONTENT, M57_STATUS_LABEL: STATUS_LABEL });

/* PlanView — rendert Seite 1 eines Grundriss-PDFs client-seitig via pdf.js in
   ein Canvas. Zuverlässig ohne PDF-Plugin/iframe. Zeigt Ladezustand + Fallback. */
function PlanView({ src, label }) {
  const canvasRef = React.useRef(null);
  const [state, setState] = React.useState('loading');
  React.useEffect(() => {
    let cancelled = false;
    setState('loading');
    const lib = window.pdfjsLib;
    if (!lib) { setState('error'); return; }
    (async () => {
      try {
        const doc = await lib.getDocument(src).promise;
        const page = await doc.getPage(1);
        if (cancelled) return;
        const canvas = canvasRef.current;
        if (!canvas) return;
        const cw = canvas.parentElement.clientWidth || 640;
        const v1 = page.getViewport({ scale: 1 });
        const scale = Math.min(2, (cw * (window.devicePixelRatio || 1)) / v1.width);
        const vp = page.getViewport({ scale });
        canvas.width = Math.ceil(vp.width);
        canvas.height = Math.ceil(vp.height);
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = '#FBF9F4';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        await page.render({ canvasContext: ctx, viewport: vp }).promise;
        if (!cancelled) setState('done');
      } catch (e) { if (!cancelled) setState('error'); }
    })();
    return () => { cancelled = true; };
  }, [src]);
  return (
    <div style={{ position: 'relative', border: '1px solid var(--sandstein)', background: 'var(--warmweiss)', minHeight: 'clamp(280px, 42vh, 460px)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
      <canvas ref={canvasRef} style={{ display: state === 'done' ? 'block' : 'none', width: '100%', height: 'auto' }}></canvas>
      {state !== 'done' && (
        <div style={{ textAlign: 'center', color: 'var(--umbra-60)', fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', padding: 'var(--space-6)' }}>
          {state === 'loading' ? 'Grundriss wird geladen …' : (
            <span>Grundriss {label || ''}<br /><a href={src} target="_blank" rel="noopener" style={{ color: 'var(--waldgruen)' }}>als PDF öffnen ↗</a></span>
          )}
        </div>
      )}
    </div>
  );
}
window.PlanView = PlanView;

/* Ultraleichte Linien-Icons (stroke 1, keine Kreise, kein Fill) für die
   Highlight-Zeile der Kategorie-Karten. Jedes Icon steht für ein Merkmal. */
function LineIcon({ name, size = 20 }) {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1, strokeLinecap: 'square', strokeLinejoin: 'miter', 'aria-hidden': true };
  const paths = {
    garten: <><path d="M12 21V11" /><path d="M12 11c0-3 2-5 5-5-.3 3-2.5 5-5 5Z" /><path d="M12 13c0-2.5-2-4.5-5-4.5.3 2.7 2.5 4.5 5 4.5Z" /><line x1="4" y1="21" x2="20" y2="21" /></>,
    terrasse: <><line x1="3" y1="20" x2="21" y2="20" /><path d="M5 20v-6h14v6" /><line x1="5" y1="14" x2="19" y2="14" /><line x1="9" y1="14" x2="9" y2="20" /><line x1="15" y1="14" x2="15" y2="20" /></>,
    balkon: <><line x1="4" y1="9" x2="20" y2="9" /><line x1="4" y1="9" x2="4" y2="20" /><line x1="20" y1="9" x2="20" y2="20" /><line x1="8" y1="9" x2="8" y2="20" /><line x1="12" y1="9" x2="12" y2="20" /><line x1="16" y1="9" x2="16" y2="20" /><line x1="4" y1="20" x2="20" y2="20" /></>,
    dachterrasse: <><path d="M3 11 12 5l9 6" /><line x1="5" y1="11" x2="5" y2="20" /><line x1="19" y1="11" x2="19" y2="20" /><line x1="5" y1="20" x2="19" y2="20" /><line x1="9" y1="15" x2="15" y2="15" /></>,
    zimmer: <><rect x="4" y="4" width="16" height="16" /><line x1="12" y1="4" x2="12" y2="20" /><line x1="12" y1="12" x2="20" y2="12" /></>,
    flaeche: <><rect x="4" y="4" width="16" height="16" /><polyline points="4,9 9,9 9,4" /><polyline points="20,15 15,15 15,20" /></>,
    ausrichtung: <><path d="M12 3v18" /><path d="M3 12h18" /><path d="m12 3 3 4h-6z" /></>,
    licht: <><circle cx="12" cy="12" r="4" /><line x1="12" y1="3" x2="12" y2="6" /><line x1="12" y1="18" x2="12" y2="21" /><line x1="3" y1="12" x2="6" y2="12" /><line x1="18" y1="12" x2="21" y2="12" /></>,
  };
  return <svg {...p}>{paths[name] || paths.zimmer}</svg>;
}
window.LineIcon = LineIcon;
