// Maison 57 — Vormerkung. Exported as an embeddable section and a standalone screen.
const {
  Button: VBtn, LineInput, LineSelect, Divider: VDivider,
} = window.Maison57DesignSystem_40d525;

/* Formular fuer Vormerkung, Kontakt und Wohnungsanfragen. Sendet an /api/inquiry (Immobilien-Master): die Anfrage wird
   in der Datenbank gesichert, per Mail an den Vertrieb geschickt und bei konkreten Wohnungen an Justimmo weitergeleitet.
   einheiten: Wohnungen aus dem Finder (Einheiten-Objekte aus data.js), quelle: 'vormerkung' | 'kontakt' | 'finder'.
   "Danke" erscheint erst, wenn der Server die Anfrage angenommen hat. */
const vEinheitText = (u) => [`Haus ${u.haus}, Top ${u.top}`, u.zimmer ? `${u.zimmer} Zimmer` : null, u.flaeche ? `${u.flaeche} m²` : null, u.freiflaecheM2 || null].filter(Boolean).join(', ');

function VormerkungForm({ prefillTop, einheiten = [], quelle = 'vormerkung', onSubmit }) {
  const [sent, setSent] = React.useState(false);
  const [senden, setSenden] = React.useState(false);
  const [fehler, setFehler] = React.useState('');
  const [showMsg, setShowMsg] = React.useState(false);
  const namen = einheiten.map((u) => `Haus ${u.haus}, Top ${u.top}`);
  const label = prefillTop || (namen.length > 1 ? namen.slice(0, -1).join(', ') + ' und ' + namen[namen.length - 1] : (namen[0] || ''));
  const submit = async (e) => {
    e.preventDefault();
    if (senden) return;
    const fd = new FormData(e.currentTarget);
    const wert = (k) => String(fd.get(k) || '').trim();
    setFehler('');
    if (!wert('name') || !wert('email') || !wert('phone')) { setFehler('Bitte Name, E-Mail und Telefon angeben.'); return; }
    setSenden(true);
    try {
      const r = await fetch('/api/inquiry', {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
        body: JSON.stringify({
          source: einheiten.length ? 'finder' : quelle,
          einheiten: einheiten.map((u) => u.id),
          unit_summary: einheiten.length ? einheiten.map(vEinheitText).join('; ') : null,
          name: wert('name'), email: wert('email'), phone: wert('phone'),
          interest: wert('interesse'), rooms: wert('zimmer'), budget: wert('budget'), message: wert('msg'),
          consent: true, // Zustimmung durch Absenden, siehe Hinweis unter dem Button
          website: wert('website'), // Honeypot
        }),
      });
      const d = await r.json().catch(() => ({}));
      if (!r.ok || d.ok === false) throw new Error(d.error || 'Die Anfrage konnte gerade nicht gesendet werden. Bitte versuchen Sie es in Kürze noch einmal oder schreiben Sie an sales@waldrain.at.');
      setSent(true);
      if (onSubmit) onSubmit();
    } catch (err) {
      setFehler(err.message && err.message !== 'Failed to fetch' ? err.message : 'Keine Verbindung. Bitte versuchen Sie es in Kürze noch einmal oder schreiben Sie an sales@waldrain.at.');
    } finally { setSenden(false); }
  };
  if (sent) {
    const plan = einheiten.length === 1 && window.M57_PLAN ? einheiten[0] : null;
    return (
      <div style={{ padding: 'var(--space-8) 0' }}>
        <svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true" style={{ display: 'block', marginBottom: 'var(--space-5)' }}>
          <path d="M6 18 L14 26 L28 9" fill="none" stroke="var(--waldgruen)" strokeWidth="1.5" pathLength="1"
            style={{ strokeDasharray: 1, strokeDashoffset: 0, animation: 'm57check 700ms var(--ease-reveal) both' }} />
          <style>{`@keyframes m57check { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }
            @media (prefers-reduced-motion: reduce) { [style*='m57check'] { animation: none !important; } }`}</style>
        </svg>
        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'var(--text-title)', color: 'var(--umbra)', margin: '0 0 var(--space-4)' }}>
          Danke für Ihre {label ? <>Anfrage zu {label}</> : 'Vormerkung'}.
        </h3>
        <p style={{ margin: '0 0 var(--space-5)', color: 'var(--umbra-90)', maxWidth: '28rem' }}>
          Die nächsten Schritte: Viola Dollinger ruft Sie innerhalb von 24 Stunden zurück, vorweg erhalten Sie die Unterlagen zum Projekt per E-Mail.
        </p>
        {plan && (
          <a href={window.M57_PLAN.href(plan)} download={window.M57_PLAN.downloadName(plan)} style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--waldgruen)', textDecoration: 'underline', textUnderlineOffset: '0.2em' }}>
            Verkaufsplan Haus {plan.haus}, Top {plan.top} als PDF
          </a>
        )}
      </div>
    );
  }
  return (
    <form onSubmit={submit} noValidate style={{ display: 'grid', gap: 'var(--space-6)' }}>
      {label && (
        <div style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--umbra)', borderBottom: '1px solid var(--sandstein)', paddingBottom: 'var(--space-3)' }}>
          Ihre Anfrage zu <span style={{ fontWeight: 500 }}>{label}</span>
        </div>
      )}
      {/* Honeypot gegen Spam-Bots, fuer Menschen unsichtbar */}
      <input type="text" name="website" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px', opacity: 0 }} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-6)' }}>
        <LineInput label="Name" name="name" placeholder="Vor- und Nachname" autoComplete="name" required />
        <LineInput label="E-Mail" name="email" type="email" placeholder="name@beispiel.at" required />
        <LineInput label="Telefon" name="phone" type="tel" placeholder="+43" required />
        <LineSelect label="Interesse" name="interesse" options={[{ value: '', label: 'Bitte wählen' }, 'Eigennutzung', 'Anlage', 'Beides']} />
        <LineSelect label="Zimmerwunsch" name="zimmer" options={[{ value: '', label: 'Bitte wählen' }, '2', '3', '4']} />
        <LineInput label="Budget (ungefähr)" name="budget" placeholder="z. B. 500.000 €" />
      </div>
      {showMsg ? (
        <LineInput label="Nachricht (optional)" name="msg" as="textarea" rows={3} />
      ) : (
        <button type="button" onClick={() => setShowMsg(true)}
          style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--umbra-60)', textDecoration: 'underline', textUnderlineOffset: '0.2em' }}>
          Nachricht hinzufügen
        </button>
      )}
      <div style={{ marginTop: 'var(--space-2)' }}>
        <VBtn variant="filled" type="submit" disabled={senden}>{senden ? 'Wird gesendet' : (label ? 'Anfrage senden' : 'Vormerkung anfragen')}</VBtn>
        {fehler && <p role="alert" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: '#9B2C1C', margin: 'var(--space-4) 0 0', maxWidth: '28rem' }}>{fehler}</p>}
        <p style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--umbra-90)', margin: 'var(--space-4) 0 0', maxWidth: '28rem' }}>
          Persönliche Rückmeldung innerhalb von 24 Stunden durch Ihre Ansprechpartnerin Viola Dollinger.
        </p>
      </div>
      <p style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-micro)', color: 'var(--umbra-60)', margin: 0, maxWidth: '28rem', lineHeight: 1.6 }}>
        Mit dem Absenden stimmen Sie der Verarbeitung Ihrer Angaben zur Bearbeitung Ihrer Anfrage zu. Es gelten unsere Datenschutzhinweise.
      </p>
    </form>
  );
}

function VormerkungSection({ prefillTop, einheiten, quelle = 'vormerkung', onSubmit, id = 'vormerkung' }) {
  const Rev = window.Maison57DesignSystem_40d525.Reveal;
  return (
    <section id={id} style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: 'clamp(11rem, 18vw, 17rem) var(--page-inset-lg)' }}>
      <Rev y={24}>
      <div className="m57-vormerkung" style={{
        display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 'clamp(3rem, 6vw, 6rem)',
        borderTop: '1px solid var(--sandstein)',
        paddingTop: 'clamp(2.5rem, 5vw, 4rem)',
      }}>
        <div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(2rem, 3.6vw, 3.25rem)', letterSpacing: '-0.01em', color: 'var(--umbra)', margin: '0 0 var(--space-6)', lineHeight: 1.08 }}>
            Sichern Sie sich Ihre <span style={{ fontStyle: 'italic' }}>Vormerkung</span>.
          </h2>
          <p style={{ margin: '0 0 var(--space-4)', color: 'var(--umbra-90)', maxWidth: '34ch' }}>
            31 Einheiten, zwei Häuser. Die Vormerkung ist unverbindlich und kostenlos.
          </p>
          <p style={{ margin: 0, color: 'var(--umbra-90)', maxWidth: '34ch' }}>
            Persönliche Rückmeldung innerhalb von 24 Stunden, durch Ihre Ansprechpartnerin Viola Dollinger.
          </p>
          <div style={{ marginTop: 'var(--space-6)', borderTop: '1px solid var(--sandstein)', paddingTop: 'var(--space-4)', fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--umbra)', lineHeight: 1.9 }}>
            Viola Dollinger, Vertrieb<br />
            <a href="mailto:sales@waldrain.at">sales@waldrain.at</a><br />
            <a href="tel:+436764347384">+43 676 434 73 84</a><br />
            <a href="tel:+4315853663">+43 1 585 36 63</a>
          </div>
        </div>
        <VormerkungForm prefillTop={prefillTop} einheiten={einheiten} quelle={quelle} onSubmit={onSubmit} />
      </div>
      </Rev>
    </section>
  );
}

function VormerkungScreen({ prefillTop, onSubmit }) {
  return (
    <div style={{ minHeight: '70vh', paddingTop: 'clamp(6rem, 10vw, 9rem)' }}>
      <div style={{ maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--page-inset-lg)' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(2.5rem, 4.5vw, 4rem)', letterSpacing: '-0.015em', color: 'var(--umbra)', margin: 0 }}>Kontakt und Vormerkung</h1>
        <p style={{ color: 'var(--umbra-90)', marginTop: 'var(--space-4)' }}>Wir freuen uns auf Ihre Anfrage.</p>
      </div>
      <VormerkungSection prefillTop={prefillTop} quelle="kontakt" onSubmit={onSubmit} id="vormerkung-page" />
    </div>
  );
}

/* AnfrageModal — Popup für die direkte Anfrage zu einer Wohnung: zentriertes
   Warmweiß-Panel mit Hairline, Kopfzeile "Anfrage zu Top X" + Schließen,
   darin das vorbefüllte Formular. Kein Routing zur Kontaktseite. */
function AnfrageModal({ unit, onClose }) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (unit) {
      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setShown(true); return; }
      const t = setTimeout(() => setShown(true), 30);
      return () => clearTimeout(t);
    }
    setShown(false);
  }, [unit]);
  if (!unit) return null;
  const close = () => { setShown(false); setTimeout(onClose, 280); };
  return (
    <div onClick={close} style={{ position: 'fixed', inset: 0, zIndex: 110, background: 'rgba(35,42,32,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-5)', opacity: shown ? 1 : 0, transition: 'opacity 280ms var(--ease-reveal)' }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label={'Anfrage zu Top ' + unit.top}
        style={{ width: 'min(720px, 100%)', maxHeight: '90vh', overflowY: 'auto', background: 'var(--warmweiss)',
          transform: shown ? 'none' : 'translateY(16px)', opacity: shown ? 1 : 0,
          transition: 'transform 380ms var(--ease-reveal), opacity 280ms var(--ease-reveal)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 'var(--space-6)', padding: 'var(--space-6) var(--space-8)', borderBottom: '1px solid var(--sandstein)' }}>
          <div>
            <div className="tabular" style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-title)', color: 'var(--umbra)', fontVariantNumeric: 'tabular-nums' }}>Anfrage zu Top {unit.top}</div>
            <div className="tabular" style={{ fontFamily: 'var(--font-text)', fontSize: 'var(--text-label)', color: 'var(--umbra-60)', marginTop: '0.3rem', fontVariantNumeric: 'tabular-nums' }}>
              Haus {unit.haus}, {unit.zimmer} Zimmer, {unit.flaeche} m², {unit.freiflaecheM2}
            </div>
          </div>
          <button onClick={close} aria-label="Schließen" style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: '1.3rem', color: 'var(--umbra-60)', lineHeight: 1, padding: 0 }}>✕</button>
        </div>
        <div style={{ padding: 'var(--space-8)' }}>
          {unit.plan && (
            <button type="button" onClick={() => window.M57ZeigePlan && window.M57ZeigePlan(unit)}
              style={{ display: 'inline-block', marginBottom: 'var(--space-5)', background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'var(--font-text)', fontSize: 'var(--text-small)', color: 'var(--waldgruen)', textDecoration: 'underline', textUnderlineOffset: '0.2em' }}>
              Grundriss Top {unit.top} ansehen
            </button>
          )}
          <VormerkungForm einheiten={[unit]} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { VormerkungSection, VormerkungScreen, VormerkungForm, AnfrageModal });
