/* Corsa Privata — "Begin": the single conversion destination. One section, two
 * ways in: book a call (Google Calendar embed slot) or send a brief (form, seeded
 * by the configurator). Copy comes from the active language (t). */
const { Eyebrow, Input, Select, Checkbox, Button, Toast, LiveIndicator, Divider } = window.CorsaPrivataDesignSystem_94a5c9;
const BeginIcon = window.Icon;
/* Multi-line brief field, matching the DS Input look (defined in Configurator.jsx). */
const BeginTextarea = window.CPTextarea;
const EXPECT_ICONS = ['clock', 'user-round', 'lock', 'mail'];

/* Google Calendar appointment schedule (official embed URL). */
const GCAL_URL = 'https://calendar.google.com/calendar/appointments/schedules/AcZssZ3sMf9aa5dGfJQ_GiEhP1UzBkKWlITX-1qZaFxRpnBcLeLqdmA3zdsHnddNfnp79EDAU7pGC0nq?gv=true';

function Begin({ t }) {
  const b = t.begin;
  const fm = b.form;
  const [tab, setTab] = React.useState('call');
  const [circuit, setCircuit] = React.useState(null);
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [interestIdx, setInterestIdx] = React.useState(0);
  const [message, setMessage] = React.useState('');
  const [agree, setAgree] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);

  React.useEffect(() => {
    // The configurator hands over the composed brief; a discipline CTA hands
    // over an interest line. Both land the visitor on the brief tab, prefilled.
    const onCircuit = (e) => {
      const c = e.detail || window.cpCircuit;
      if (!c) return;
      setCircuit(c);
      setTab('brief');
      setMessage((fm.circuitIntro ? fm.circuitIntro + '\n' : '') + c.summary + '\n');
      if (c.name) setName(c.name);
      if (c.email) setEmail(c.email);
    };
    const onInterest = (e) => {
      const d = e.detail || {};
      if (!d.name) return;
      setTab('brief');
      setMessage((m) => (m.trim() ? m : fm.interestIntro.replace('{name}', d.name) + '\n'));
    };
    window.addEventListener('cp:circuit', onCircuit);
    window.addEventListener('cp:interest', onInterest);
    return () => {
      window.removeEventListener('cp:circuit', onCircuit);
      window.removeEventListener('cp:interest', onInterest);
    };
  }, [t]);

  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!name.trim()) er.name = fm.nameErr;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) er.email = fm.emailErr;
    if (!agree) er.agree = true;
    setErrors(er);
    if (Object.keys(er).length) return;
    const r = await (window.cpSubmitBrief
      ? window.cpSubmitBrief({
          _subject: 'Consulta — Corsa Privata',
          _replyto: email.trim(),
          name: name.trim(),
          email: email.trim(),
          interes: fm.interestOptions[interestIdx],
          mensaje: message.trim(),
          idioma: t.langLabel,
        })
      : Promise.resolve({ ok: false, skipped: true }));
    if (!r.ok && !r.skipped) { setErrors({ send: true }); return; }
    setSent(true);
    window.setTimeout(() => setSent(false), 5000);
  };

  return (
    <section id="begin" style={{ position: 'relative', background: 'var(--surface-page)', overflow: 'hidden', scrollMarginTop: 0 }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, backgroundImage: 'var(--gradient-gold)', opacity: 0.7 }} />
      <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: 'clamp(76px,9vw,118px) 32px' }}>
        <div className="cp-begin-grid" style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: 56, alignItems: 'start' }}>
          <div className="cp-reveal">
            <Eyebrow tone="gold">{b.eyebrow}</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-bold)', fontSize: 'clamp(34px,4.4vw,54px)', lineHeight: 1.02, letterSpacing: '-0.03em', color: 'var(--text-strong)', margin: '16px 0 0', textWrap: 'balance' }}>
              {b.h2}
            </h2>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 'clamp(16px,1.4vw,18px)', lineHeight: 1.6, color: 'var(--text-body)', margin: '18px 0 0', maxWidth: '44ch', textWrap: 'pretty' }}>
              {b.sub}
            </p>
            <div style={{ marginTop: 24 }}>
              <LiveIndicator label={b.concierge} color="var(--cp-success)" />
            </div>

            <div className="cp-expect-grid" style={{ marginTop: 36, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '22px 28px' }}>
              {b.expect.map((x, i) => (
                <div key={x.t} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <BeginIcon name={EXPECT_ICONS[i]} size={18} stroke={1.5} color="var(--cp-gold-700)" style={{ marginTop: 2, flex: 'none' }} />
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 15, color: 'var(--text-strong)', letterSpacing: '-0.01em' }}>{x.t}</div>
                    <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.5, color: 'var(--text-muted)', marginTop: 3 }}>{x.d}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="cp-reveal" style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border-hairline)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden' }}>
            <div style={{ display: 'flex', gap: 6, padding: 8, background: 'var(--surface-sunken)', borderBottom: '1px solid var(--border-hairline)' }}>
              {[{ id: 'call', label: b.tabCall, icon: 'calendar' }, { id: 'brief', label: b.tabBrief, icon: 'send' }].map((tb) => {
                const on = tab === tb.id;
                return (
                  <button key={tb.id} onClick={() => setTab(tb.id)} style={{
                    flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 9, cursor: 'pointer',
                    padding: '11px 14px', borderRadius: 'var(--radius-sm)', border: '1px solid', borderColor: on ? 'rgba(194,161,101,0.4)' : 'transparent',
                    background: on ? 'var(--surface-card)' : 'transparent', boxShadow: on ? 'var(--shadow-xs)' : 'none',
                    fontFamily: 'var(--font-display)', fontSize: 12, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wider)', textTransform: 'uppercase',
                    color: on ? 'var(--text-strong)' : 'var(--text-muted)', transition: 'all var(--dur-fast) var(--ease-standard)',
                  }}>
                    <BeginIcon name={tb.icon} size={15} stroke={1.6} color={on ? 'var(--cp-gold-700)' : 'var(--text-muted)'} />
                    {tb.label}
                  </button>
                );
              })}
            </div>

            {tab === 'call' ? (
              /* Google Calendar appointment scheduling (official embed). White
               * canvas behind the iframe so Google's page never sits on sunken grey. */
              <div style={{ padding: 'var(--space-6)' }}>
                <div className="cp-scheduler" style={{ borderRadius: 'var(--radius-md)', border: '1px solid var(--border-hairline)', background: '#FFFFFF', overflow: 'hidden' }}>
                  <iframe title={b.h2} src={GCAL_URL}
                    style={{ display: 'block', width: '100%', height: 600, border: 0, background: '#FFFFFF' }} />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 14, flexWrap: 'wrap' }}>
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font-display)', fontSize: 10.5, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--text-faint)' }}>
                    <BeginIcon name="calendar" size={13} stroke={1.6} color="var(--text-faint)" /> {b.scheduler.powered}
                  </div>
                  <Button variant="ghost" onClick={() => setTab('brief')} style={{ paddingRight: 0 }}>{b.scheduler.orBrief} &nbsp;&rarr;</Button>
                </div>
              </div>
            ) : (
              <form onSubmit={submit} style={{ padding: 'var(--space-6)', display: 'flex', flexDirection: 'column', gap: 16 }}>
                {circuit && (
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '12px 14px', borderRadius: 'var(--radius-sm)', background: 'var(--cp-gold-050)', border: '1px solid rgba(194,161,101,0.3)' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--cp-gold-700)' }}>
                      <BeginIcon name="route" size={14} stroke={1.6} color="var(--cp-gold-700)" /> {fm.circuitAttached}
                    </span>
                    <BeginIcon name="check" size={15} stroke={2} color="var(--cp-gold-700)" />
                  </div>
                )}
                <div className="cp-form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <Input label={fm.name} placeholder={fm.namePh} value={name} onChange={(e) => setName(e.target.value)} error={errors.name} />
                  <Input label={fm.email} type="email" placeholder={fm.emailPh} value={email} onChange={(e) => setEmail(e.target.value)} error={errors.email} />
                </div>
                <Select label={fm.interestLabel} value={fm.interestOptions[interestIdx]}
                  onChange={(e) => setInterestIdx(Math.max(0, fm.interestOptions.indexOf(e.target.value)))}
                  options={fm.interestOptions} />
                <BeginTextarea label={fm.messageLabel} placeholder={fm.messagePh} rows={circuit ? 9 : 4} value={message} onChange={(e) => setMessage(e.target.value)} />
                {/* type="button": the DS Checkbox renders a <button> which would
                  * otherwise default to type="submit" and submit this form. */}
                <Checkbox type="button" checked={agree} onChange={(v) => { setAgree(v); setErrors((er) => ({ ...er, agree: false })); }} label={fm.consent} />
                {errors.agree && <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--cp-danger)', marginTop: -8 }}>{fm.consentErr}</span>}
                {errors.send && <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--cp-danger)', marginTop: -8 }}>{fm.sendErr}</span>}
                <Button type="submit" fullWidth>{fm.submit}</Button>
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 12, lineHeight: 1.5, color: 'var(--text-faint)', textAlign: 'center', margin: 0 }}>
                  {fm.fine}
                </p>
              </form>
            )}
          </div>
        </div>
      </div>

      {sent && (
        <div style={{ position: 'fixed', right: 24, bottom: 24, zIndex: 60 }}>
          <Toast title={b.toast.title} message={b.toast.msg} variant="success" onDismiss={() => setSent(false)} />
        </div>
      )}
    </section>
  );
}

window.Begin = Begin;
