/* Contact — Custom form (POSTs to HubSpot Forms API) + Booking modal (iframe in chrome) */

const HS_PORTAL = '147489008';
const HS_FORM = '748f289e-4ace-4b8d-b28b-d9d2c6cd7a2a';
const HS_SHARE = 'https://2ft78w.share-eu1.hsforms.com/2dI8onkrOS42yi9nSxs16Kg';
const HS_MEETING = 'https://meetings-eu1.hubspot.com/christopher52?embed=true';

function Contact() {
  const [bookingOpen, setBookingOpen] = useState(false);
  const [bookingUrl, setBookingUrl] = useState(HS_MEETING);
  const [bookingSelection, setBookingSelection] = useState(null); // { date: ISO, time: 'HH:MM' } or null

  const openBooking = (url, selection = null) => {
    setBookingUrl(url || HS_MEETING);
    setBookingSelection(selection);
    setBookingOpen(true);
  };

  return (
    <section id="contact" className="section" style={{ background: 'var(--bg-elev)', padding: "60px 0px", fontFamily: "\"Inter Tight\"" }} data-screen-label="Contact">
      <div className="container">
        <div style={{ textAlign: 'center', marginBottom: 64 }}>
          <h2 className="display display-xl reveal" style={{ marginBottom: 24 }}>
            30 Minuten.<br /><span className="sheen">Kein Pitch-Deck.</span>
          </h2>
          <p className="body-lg reveal" style={{ maxWidth: 520, margin: '0 auto' }}>
            Slot wählen, kurz Bescheid geben worum's geht — wir bestätigen den Termin direkt.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.45fr 1fr', gap: 20 }} id="ct-grid">
          {/* Custom booking — calendar + slim form */}
          <div className="card edge-gradient reveal" style={{ padding: 40, display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 28 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <BrandMark size={24} />
                <span className="chip-dot pulse" style={{ width: 8, height: 8 }} />
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-3)', letterSpacing: '0.2em' }}>BUCHUNG · 30-MIN-CALL</span>
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>SSL · DSGVO</div>
            </div>

            <BookingForm onBook={openBooking} />

            <div className="mono" style={{ fontSize: 10, color: 'var(--text-4)', letterSpacing: '0.15em', marginTop: 18, textAlign: 'center' }}>
              FINALE BESTÄTIGUNG IM HUBSPOT-KALENDER · KEIN UMWEG
            </div>
          </div>

          {/* Right column — info + promise */}
          <div className="reveal" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <InfoBlock icon="mail" label="E-MAIL" value="info@archaitechs.de" sub="Antwort in 2h" href="mailto:info@archaitechs.de" />

            <div className="card edge-gradient" style={{ padding: 28 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.2em', marginBottom: 12 }}>VERSPRECHEN</div>
              <div className="display display-md" style={{ fontWeight: 500, marginBottom: 10, color: 'rgb(255, 255, 255)', fontFamily: "\"Inter Tight\"" }}>
                "Erster Call ist kostenlos und ehrlich. Wenn KI bei Ihnen keinen Sinn ergibt, sagen wir das auch."
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>— C. WELZ, CO-FOUNDER</div>
            </div>
          </div>
        </div>
      </div>

      {bookingOpen && <BookingModal onClose={() => setBookingOpen(false)} url={bookingUrl} selection={bookingSelection} />}

      <style>{`
        @media(max-width:980px){#ct-grid{grid-template-columns:1fr!important;}}
      `}</style>
    </section>);
}

/* ---------- Booking form — calendar + slim form, opens HubSpot modal pre-filled ---------- */

function BookingForm({ onBook }) {
  const [data, setData] = useState({ firstname: '', lastname: '', email: '', company: '', phone: '', message: '', consent: false });
  const [selectedDate, setSelectedDate] = useState(null);  // ISO YYYY-MM-DD
  const [selectedTime, setSelectedTime] = useState(null);  // HH:MM
  const [touched, setTouched] = useState({});

  const set = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.type === 'checkbox' ? e.target.checked : e.target.value }));
  const onBlur = (k) => () => setTouched((t) => ({ ...t, [k]: true }));

  // Generate next 14 weekdays (Mo–Fr), starting tomorrow
  const days = useMemo(() => {
    const out = [];
    const cursor = new Date();
    cursor.setHours(0, 0, 0, 0);
    while (out.length < 14) {
      cursor.setDate(cursor.getDate() + 1);
      const dow = cursor.getDay();
      if (dow !== 0 && dow !== 6) out.push(new Date(cursor));
    }
    return out;
  }, []);

  const times = ['09:00', '10:00', '11:00', '12:00', '14:00', '15:00', '16:00'];

  const valid =
    selectedDate &&
    selectedTime &&
    data.firstname.trim().length > 1 &&
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email) &&
    data.consent;

  function submit(e) {
    e.preventDefault();
    if (!valid) return;

    // Build HubSpot Meetings URL with pre-fill query params
    const params = new URLSearchParams();
    params.set('embed', 'true');
    if (data.firstname.trim()) params.set('firstName', data.firstname.trim());
    if (data.lastname.trim()) params.set('lastName', data.lastname.trim());
    if (data.email.trim()) params.set('email', data.email.trim());
    if (data.phone.trim()) params.set('phone', data.phone.trim());
    if (data.company.trim()) params.set('company', data.company.trim());
    if (data.message.trim()) params.set('description', data.message.trim());
    if (selectedDate) params.set('date', selectedDate);
    params.set('utm_source', 'archaitechs-site');
    params.set('utm_medium', 'embedded-booking');

    const url = `https://meetings-eu1.hubspot.com/christopher52?${params.toString()}`;
    onBook(url, { date: selectedDate, time: selectedTime });
  }

  const fmtDay = (d) => ({
    weekday: d.toLocaleDateString('de-DE', { weekday: 'short' }).replace('.', '').toUpperCase(),
    day: d.getDate(),
    month: d.toLocaleDateString('de-DE', { month: 'short' }).replace('.', '').toUpperCase(),
    iso: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  });

  const dayRow = (slice) => (
    <div className="bf-day-row" style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
      {slice.map((d) => {
        const f = fmtDay(d);
        const sel = selectedDate === f.iso;
        return (
          <button type="button" key={f.iso} onClick={() => { setSelectedDate(f.iso); setSelectedTime(null); }}
            className={`bf-day ${sel ? 'sel' : ''}`}>
            <div className="mono" style={{ fontSize: 9, opacity: 0.65, letterSpacing: '0.12em' }}>{f.weekday}</div>
            <div style={{ fontSize: 18, fontWeight: 500, lineHeight: 1.1, margin: '2px 0' }}>{f.day}</div>
            <div className="mono" style={{ fontSize: 9, opacity: 0.55, letterSpacing: '0.12em' }}>{f.month}</div>
          </button>
        );
      })}
    </div>
  );

  return (
    <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 22, flex: 1 }}>

      {/* 1. Date picker */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <label className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.2em' }}>1 · WANN PASST'S?</label>
        {dayRow(days.slice(0, 7))}
        {dayRow(days.slice(7, 14))}
      </div>

      {/* 2. Time slot picker — only when date selected */}
      {selectedDate && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <label className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.2em' }}>2 · UHRZEIT (CET)</label>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
            {times.map((t) => (
              <button type="button" key={t} onClick={() => setSelectedTime(t)}
                className={`bf-slot ${selectedTime === t ? 'sel' : ''}`}>
                {t}
              </button>
            ))}
          </div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-4)', letterSpacing: '0.1em' }}>
            * Live-Verfügbarkeit prüft HubSpot beim Bestätigen.
          </div>
        </div>
      )}

      {/* 3. Form fields — only when date + time selected */}
      {selectedDate && selectedTime && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <label className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.2em' }}>3 · KONTAKT</label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="cf-row">
            <Field label="Vorname *" id="bf-firstname">
              <input id="bf-firstname" required value={data.firstname} onChange={set('firstname')} onBlur={onBlur('firstname')}
                className="cf-input" autoComplete="given-name" />
            </Field>
            <Field label="Nachname" id="bf-lastname">
              <input id="bf-lastname" value={data.lastname} onChange={set('lastname')} onBlur={onBlur('lastname')}
                className="cf-input" autoComplete="family-name" />
            </Field>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 12 }} className="cf-row">
            <Field label="E-Mail *" id="bf-email" error={touched.email && data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email) ? 'Bitte gültige E-Mail' : null}>
              <input id="bf-email" type="email" required value={data.email} onChange={set('email')} onBlur={onBlur('email')}
                className="cf-input" autoComplete="email" />
            </Field>
            <Field label="Telefon" id="bf-phone">
              <input id="bf-phone" type="tel" value={data.phone} onChange={set('phone')} onBlur={onBlur('phone')}
                className="cf-input" autoComplete="tel" />
            </Field>
          </div>
          <Field label="Unternehmen / Maklerbüro" id="bf-company">
            <input id="bf-company" value={data.company} onChange={set('company')} onBlur={onBlur('company')}
              className="cf-input" autoComplete="organization" />
          </Field>
          <Field label="Worum geht's? (optional)" id="bf-message" hint="Welcher Bereich, was nervt am meisten.">
            <textarea id="bf-message" rows={3} value={data.message} onChange={set('message')} onBlur={onBlur('message')}
              className="cf-input" style={{ resize: 'vertical', minHeight: 72, fontFamily: 'inherit' }} />
          </Field>

          <label style={{ display: 'flex', alignItems: 'flex-start', gap: 12, cursor: 'pointer', marginTop: 2 }}>
            <input type="checkbox" checked={data.consent} onChange={set('consent')} required
              style={{ marginTop: 3, width: 16, height: 16, accentColor: 'var(--accent)', flexShrink: 0 }} />
            <span style={{ fontSize: 12, color: 'var(--text-3)', lineHeight: 1.5 }}>
              Ich willige ein, dass archaitechs meine Angaben zur Terminvereinbarung verarbeitet. Details in der <a href="#datenschutz" style={{ color: 'var(--text-2)', textDecoration: 'underline' }}>Datenschutzerklärung</a>. *
            </span>
          </label>
        </div>
      )}

      {/* Submit */}
      <button type="submit" disabled={!valid}
        className="btn btn-primary" style={{ marginTop: 4, alignSelf: 'flex-start', opacity: !valid ? 0.55 : 1, cursor: !valid ? 'not-allowed' : 'pointer' }}>
        <span>Termin verbindlich buchen</span>
        <Icon name="arrow" size={14} />
      </button>

      <style>{`
        .cf-input {
          width: 100%;
          background: rgba(255,255,255,0.02);
          border: 1px solid var(--border);
          border-radius: 8px;
          color: var(--text);
          font-family: inherit;
          font-size: 14px;
          padding: 12px 14px;
          transition: border-color .2s, background .2s;
          outline: none;
        }
        .cf-input:hover { border-color: var(--text-4); }
        .cf-input:focus { border-color: var(--text-2); background: rgba(255,255,255,0.04); }
        .cf-input::placeholder { color: var(--text-4); }
        @media(max-width:560px){
          .cf-row{ grid-template-columns: 1fr !important; }
          .bf-day-row{ grid-template-columns: repeat(4, 1fr) !important; }
        }

        .bf-day {
          background: rgba(255,255,255,0.02);
          border: 1px solid var(--border);
          border-radius: 10px;
          color: var(--text);
          padding: 12px 4px;
          cursor: pointer;
          display: flex;
          flex-direction: column;
          align-items: center;
          transition: all .2s var(--ease-out);
          font-family: inherit;
        }
        .bf-day:hover { border-color: var(--text-4); background: rgba(255,255,255,0.04); }
        .bf-day.sel {
          background: var(--accent);
          color: #0a0a0a;
          border-color: var(--accent);
        }
        .bf-day.sel * { color: #0a0a0a !important; opacity: 1 !important; }

        .bf-slot {
          background: rgba(255,255,255,0.02);
          border: 1px solid var(--border);
          border-radius: 10px;
          color: var(--text);
          padding: 12px 4px;
          cursor: pointer;
          font-family: inherit;
          font-size: 13px;
          font-weight: 500;
          transition: all .2s var(--ease-out);
          letter-spacing: 0.02em;
        }
        .bf-slot:hover { border-color: var(--text-4); background: rgba(255,255,255,0.04); }
        .bf-slot.sel {
          background: var(--accent);
          color: #0a0a0a;
          border-color: var(--accent);
        }
      `}</style>
    </form>);
}

function Field({ label, id, hint, error, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label htmlFor={id} className="mono" style={{ fontSize: 10, color: error ? '#ff7a7a' : 'var(--text-3)', letterSpacing: '0.2em', textTransform: 'uppercase' }}>{label}</label>
      {children}
      {(hint || error) &&
      <div className="mono" style={{ fontSize: 10, color: error ? '#ff7a7a' : 'var(--text-4)', letterSpacing: '0.05em' }}>
          {error || hint}
        </div>}
    </div>);
}

/* ---------- Booking modal — frames the HubSpot iframe in our chrome ---------- */

function BookingModal({ onClose, url, selection }) {
  const iframeUrl = url || HS_MEETING;

  // Format selection for prominent display in modal header
  const selDisplay = useMemo(() => {
    if (!selection || !selection.date || !selection.time) return null;
    const [y, m, d] = selection.date.split('-').map(Number);
    const dateObj = new Date(y, m - 1, d);
    const dayName = dateObj.toLocaleDateString('de-DE', { weekday: 'long' });
    const dateStr = dateObj.toLocaleDateString('de-DE', { day: 'numeric', month: 'long' });
    return { line: `${dayName}, ${dateStr}`, time: selection.time };
  }, [selection]);

  useEffect(() => {
    const onKey = (e) => {if (e.key === 'Escape') onClose();};
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {document.removeEventListener('keydown', onKey);document.body.style.overflow = prevOverflow;};
  }, [onClose]);

  return (
    <div onClick={onClose}
    style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.78)',
      backdropFilter: 'blur(8px)',
      WebkitBackdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20,
      animation: 'bm-fade .25s var(--ease-out)'
    }}>
      <div onClick={(e) => e.stopPropagation()}
      className="card"
      style={{
        width: 'min(1100px, 100%)',
        height: 'min(900px, 94vh)',
        maxHeight: '94vh',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
        background: 'var(--bg-elev)',
        border: '1px solid var(--border)',
        animation: 'bm-pop .35s var(--ease-out)'
      }}>
        {/* Chrome header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px', borderBottom: '1px solid var(--border)', background: 'rgba(255,255,255,0.02)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <BrandMark size={20} />
            <span className="chip-dot pulse" style={{ width: 7, height: 7 }} />
            <span className="mono" style={{ fontSize: 11, color: 'var(--text-3)', letterSpacing: '0.22em' }}>TERMIN · 30-MIN-CALL</span>
          </div>
          <button onClick={onClose} aria-label="Schließen"
          style={{ width: 36, height: 36, borderRadius: 8, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border)', color: 'var(--text-2)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="close" size={16} />
          </button>
        </div>

        {/* Selection callout — only when user came from BookingForm with picked date+time */}
        {selDisplay && (
          <div style={{
            padding: '24px 28px',
            background: 'color-mix(in oklab, var(--accent) 22%, var(--bg-elev))',
            borderBottom: '2px solid var(--accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap',
            boxShadow: '0 1px 0 0 color-mix(in oklab, var(--accent) 30%, transparent) inset'
          }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.28em', fontWeight: 600 }}>IHRE WUNSCH-AUSWAHL</div>
              <div style={{ fontSize: 26, fontWeight: 600, color: '#fff', letterSpacing: '-0.015em', lineHeight: 1.15 }}>
                {selDisplay.line} <span style={{ color: 'var(--accent)' }}>·</span> <span style={{ fontVariantNumeric: 'tabular-nums', color: 'var(--accent)' }}>{selDisplay.time}</span> <span style={{ color: 'var(--text-2)', fontWeight: 400, fontSize: 22 }}>Uhr</span>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end' }}>
              <div className="mono bm-pulse" style={{ fontSize: 12, color: 'var(--accent)', letterSpacing: '0.22em', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 16, lineHeight: 1 }}>↓</span> IM KALENDER BESTÄTIGEN
              </div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.18em' }}>
                ODER ANDEREN SLOT WÄHLEN
              </div>
            </div>
          </div>
        )}

        {/* Iframe area — HubSpot Meetings calendar (URL pre-filled with selection from BookingForm) */}
        <div style={{ flex: 1, position: 'relative', background: '#fff', minHeight: 700, overflow: 'auto' }}>
          <iframe
            src={iframeUrl}
            title="Termin-Slot buchen"
            style={{ width: '100%', height: '100%', border: 0, display: 'block', minHeight: 800 }}
            allow="clipboard-write; geolocation; camera; microphone" />

        </div>

        {/* Chrome footer */}
        <div style={{ padding: '12px 20px', borderTop: '1px solid var(--border)', background: 'rgba(255,255,255,0.02)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-4)', letterSpacing: '0.18em' }}>SSL · DSGVO · ESC ZUM SCHLIESSEN</div>
          <a href={iframeUrl} target="_blank" rel="noopener noreferrer" className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.18em', textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            IN NEUEM TAB <Icon name="arrow" size={11} />
          </a>
        </div>
      </div>

      <style>{`
        @keyframes bm-fade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes bm-pop  { from { opacity: 0; transform: translateY(12px) scale(.98) } to { opacity: 1; transform: translateY(0) scale(1) } }
        @keyframes bm-pulse-arrow { 0%, 100% { transform: translateY(0); opacity: 1 } 50% { transform: translateY(2px); opacity: 0.7 } }
        .bm-pulse > span:first-child { animation: bm-pulse-arrow 1.6s ease-in-out infinite; display: inline-block; }
      `}</style>
    </div>);
}

/* ---------- Info block (right column) ---------- */

function InfoBlock({ icon, label, value, sub, href }) {
  const Wrap = href ? 'a' : 'div';
  return (
    <Wrap href={href} className="card" style={{
      padding: 24, display: 'flex', alignItems: 'center', gap: 18,
      textDecoration: 'none', color: 'var(--text)'
    }}>
      <div style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={icon} size={18} />
      </div>
      <div style={{ flex: 1 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.2em', marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 17, fontWeight: 500 }}>{value}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--text-4)', marginTop: 2 }}>{sub}</div>
      </div>
      <Icon name="arrow" size={16} style={{ color: 'var(--text-3)' }} />
    </Wrap>);
}

Object.assign(window, { Contact });