// MapHero — left title / right map split, with a single Cramer 1616 parcel
// card on the right that rotates between Aérea / Parcela / Planta views.

const { useState, useEffect } = React;

// ─────────────────────────────────────────────────────────────────────────────
// MapStage — diagonal city-block grid with three decorative parcel highlights.
// ─────────────────────────────────────────────────────────────────────────────

const STREET_NAMES_H = ['Honduras', 'El Salvador', 'Costa Rica', 'Nicaragua', 'Gorriti', 'Cabrera'];
const STREET_NAMES_V = ['Armenia', 'Malabia', 'Thames', 'Serrano', 'Bonpland'];

// Static positions for the three decorative blue parcels.
const HIGHLIGHTS = [
  { bx: 2, by: 1, slot: 4 },
  { bx: 3, by: 2, slot: 1 },
  { bx: 1, by: 0, slot: 5 },
];

function MapStage() {
  const palette = { bg: '#9ed8b8', street: '#ffffff', label: '#7ab094', strokeBlock: 'rgba(0,0,0,0.04)' };
  const cols = 5, rows = 4;
  const blockW = 220, blockH = 130;
  const gap = 36; // street width

  const blocks = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      blocks.push({ x: c * (blockW + gap), y: r * (blockH + gap), w: blockW, h: blockH, id: `b${r}-${c}` });
    }
  }

  function blockParcels(block, blockKey) {
    const slivers = 8;
    const sliverW = (block.w - 18) / slivers;
    const out = [];
    for (let i = 0; i < slivers; i++) {
      out.push(
        <rect
          key={`${blockKey}-s${i}`}
          x={block.x + 9 + i * sliverW}
          y={block.y + 9}
          width={sliverW - 1.5}
          height={block.h - 18}
          fill={palette.bg}
          stroke={palette.strokeBlock}
          strokeWidth="0.6"
          rx="1"
        />
      );
    }
    return out;
  }

  function highlightRect(pos) {
    const block = blocks.find(b => b.id === `b${pos.by}-${pos.bx}`);
    if (!block) return null;
    const slivers = 8;
    const sliverW = (block.w - 18) / slivers;
    return {
      x: block.x + 9 + pos.slot * sliverW,
      y: block.y + 9,
      w: sliverW - 1.5,
      h: block.h - 18,
    };
  }

  const totalW = cols * (blockW + gap);
  const totalH = rows * (blockH + gap);

  return (
    <svg
      viewBox={`0 0 ${totalW} ${totalH}`}
      preserveAspectRatio="xMidYMid slice"
      style={{ width: '100%', height: '100%', display: 'block' }}
    >
      <rect x="-200" y="-200" width={totalW + 400} height={totalH + 400} fill={palette.street} />
      <g transform={`rotate(-12 ${totalW / 2} ${totalH / 2})`}>
        {blocks.map(b => (
          <rect key={b.id} x={b.x} y={b.y} width={b.w} height={b.h} fill={palette.bg} rx="2" />
        ))}
        {blocks.map(b => blockParcels(b, b.id))}

        {Array.from({ length: rows - 1 }).map((_, i) => {
          const y = (i + 1) * (blockH + gap) - gap / 2;
          return (
            <text
              key={`hl-${i}`}
              x={totalW / 2}
              y={y + 4}
              textAnchor="middle"
              fill={palette.label}
              fontFamily="DM Mono, monospace"
              fontSize="11"
              letterSpacing="2"
              style={{ textTransform: 'uppercase' }}
            >
              {STREET_NAMES_H[i % STREET_NAMES_H.length]}
            </text>
          );
        })}

        {Array.from({ length: cols - 1 }).map((_, i) => {
          const x = (i + 1) * (blockW + gap) - gap / 2;
          return (
            <text
              key={`vl-${i}`}
              x={x}
              y={totalH / 2}
              textAnchor="middle"
              fill={palette.label}
              fontFamily="DM Mono, monospace"
              fontSize="11"
              letterSpacing="2"
              transform={`rotate(-90 ${x} ${totalH / 2})`}
              style={{ textTransform: 'uppercase' }}
            >
              {STREET_NAMES_V[i % STREET_NAMES_V.length]}
            </text>
          );
        })}

        {blocks.map((b, i) => {
          if (i % 3 !== 0) return null;
          const num = 1700 + (i * 100) % 900;
          return (
            <text
              key={`num-${b.id}`}
              x={b.x + b.w - 8}
              y={b.y + 14}
              textAnchor="end"
              fill={palette.label}
              fontFamily="DM Mono, monospace"
              fontSize="9"
              opacity="0.7"
            >
              {num}
            </text>
          );
        })}

        {HIGHLIGHTS.map((pos, i) => {
          const r = highlightRect(pos);
          if (!r) return null;
          return (
            <rect
              key={`hi-${i}`}
              x={r.x} y={r.y} width={r.w} height={r.h}
              fill="rgba(24,95,165,0.08)"
              stroke="#185FA5"
              strokeWidth="1.4"
              rx="1.5"
            />
          );
        })}
      </g>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// CramerCard — single parcela view that rotates between Aérea / Parcela / Planta.
// ─────────────────────────────────────────────────────────────────────────────

const ANGLES = [
  { label: 'Aérea',   src: 'assets/cramer-views/aerea.svg',   alt: 'Vista aérea — manzana y parcela en contexto' },
  { label: 'Parcela', src: 'assets/cramer-views/parcela.svg', alt: 'Envolvente edificable de la parcela aislada' },
  { label: 'Planta',  src: 'assets/cramer-views/planta.svg',  alt: 'Vista en planta — manzana desde arriba' },
];

const PIN_SVG = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" />
    <circle cx="12" cy="10" r="3" />
  </svg>
);

const PLUS_ICON = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 3v16a2 2 0 0 0 2 2h16" />
    <path d="m19 9-5 5-4-4-3 3" />
  </svg>
);

function CramerCard() {
  const [idx, setIdx] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % ANGLES.length), 4000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="mh-card-wrap">
      <div className="mh-newcard">
        <div className="head">
          <div className="pin">{PIN_SVG}</div>
          <div>
            <div className="title">Cramer 1616</div>
            <div className="meta">037-103-033<span className="sep">·</span>COLEGIALES</div>
          </div>
        </div>

        <div className="badges">
          <span className="pill"><span className="swatch"></span>USAB2</span>
          <span className="pill fiscal">R2b I<span className="sup">FISCAL</span></span>
        </div>

        <div className="eyebrow">Envolvente edificable</div>
        <div className="vol">
          <span className="angle-tag">{ANGLES[idx].label}</span>
          {ANGLES.map((a, i) => (
            <div key={a.label} className={`slot ${i === idx ? 'active' : ''}`}>
              <img src={a.src} alt={a.alt} />
            </div>
          ))}
        </div>
        <div className="dots-row">
          {ANGLES.map((_, i) => (
            <span key={i} className={`dotitem ${i === idx ? 'active' : ''}`} />
          ))}
        </div>

        <div className="sec-label">Volumetría</div>
        <dl className="stats">
          <div className="stat"><dt>Superficie parcela</dt><dd>119,9<span className="unit">m²</span></dd></div>
          <div className="stat"><dt>Sup. edificable</dt><dd>701<span className="unit">m²</span></dd></div>
        </dl>

        <div className="sec-label">Reglas fiscales · DDHUS</div>
        <dl className="stats">
          <div className="stat"><dt>Incidencia UVA</dt><dd>380<span className="unit">UVA/m²</span></dd></div>
          <div className="stat"><dt>Costo m² premium</dt><dd>133,0<span className="unit">UVA/m²</span></dd></div>
        </dl>

        <div className="plus">
          <div className="plus-head">{PLUS_ICON}Tasación residual</div>
          <div className="plus-copy">
            Valor residual <b>US$ 395.000</b> · incidencia <b>563 USD/m²</b> sobre 701 m² edificables.
          </div>
          <div className="bar">
            <div className="bar-fiscal" style={{ width: '27.4%' }}></div>
            <div className="bar-premium" style={{ width: '72.6%' }}></div>
          </div>
          <div className="bar-labels">
            <span>base fiscal <b>192&nbsp;m²</b></span>
            <span>premium <b>509&nbsp;m²</b></span>
            <span>envolvente <b>701&nbsp;m²</b></span>
          </div>
        </div>

        <div className="footer">
          <span className="live">Datos demostrativos</span>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Hero signup form
// ─────────────────────────────────────────────────────────────────────────────

function HeroSignupForm() {
  const [status, setStatus] = useState(null);
  const [errMsg, setErrMsg] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    const form = e.target;
    const email = form.querySelector('input[name="email"]').value;
    const honeypot = form.querySelector('input[name="company"]').value;
    if (honeypot) return;

    setStatus('sending');
    fetch('/api/waitlist', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email }),
    })
      .then(r => r.json().then(d => ({ ok: r.ok, data: d })))
      .then(res => {
        if (res.ok) { setStatus('ok'); }
        else { setStatus('err'); setErrMsg(res.data.detail || 'Error, intentá de nuevo.'); }
      })
      .catch(() => { setStatus('err'); setErrMsg('Error de conexión.'); });
  }

  if (status === 'ok') {
    return <p className="cta-note mh-note cta-ok">Listo. Te mandamos tu acceso por email.</p>;
  }

  return (
    <>
      <form className="cta-form mh-form" onSubmit={handleSubmit}>
        <input type="email" name="email" placeholder="tu@email.com" required />
        <input type="text" name="company" style={{ position: 'absolute', left: '-9999px' }} tabIndex="-1" autoComplete="off" />
        <button type="submit" disabled={status === 'sending'}>
          {status === 'sending' ? 'Enviando...' : 'Tasar gratis'}
        </button>
      </form>
      {status === 'err' && <p className="cta-note mh-note cta-err">{errMsg}</p>}
    </>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// MapHero — left text + form, right map background + CramerCard.
// ─────────────────────────────────────────────────────────────────────────────

function MapHero() {
  return (
    <section className="map-hero">
      <div className="mh-mapbg mh-style-teal">
        <MapStage />
      </div>
      <div className="mh-fade" aria-hidden="true"></div>

      <div className="mh-left">
        <h1 className="mh-h1">
          Tasaciones rápidas<br />
          y confiables.
        </h1>
        <p className="mh-sub">
          PlotIQ junta la información por vos: normativa vigente, envolvente edificable
          y mercado del barrio, en una tasación de terreno por método residual,
          lista para presentar.
        </p>
        <HeroSignupForm />
      </div>

      <div className="mh-right">
        <CramerCard />
      </div>
    </section>
  );
}

const __mhRoot = document.getElementById('map-hero-root');
if (__mhRoot) {
  ReactDOM.createRoot(__mhRoot).render(<MapHero />);
}
