// ContactCalendar.jsx - booking calendar that replaces the contact form on the Deezer homepage.
// Flow: pick date → pick time → form (name/email/company/topic/notes) → thanks.
// Dostępność i rezerwacja idą przez window.BookingAPI (booking-api.js, ładowany przed tym plikiem).

function ContactCalendar() {
  const MONTHS_PL = ['styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec','sierpień','wrzesień','październik','listopad','grudzień'];
  const MONTHS_PL_DM = ['stycznia','lutego','marca','kwietnia','maja','czerwca','lipca','sierpnia','września','października','listopada','grudnia'];
  const DOW_PL = ['Pn','Wt','Śr','Cz','Pt','Sb','Nd'];
  const DOW_PL_FULL = ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'];

  const TOPICS = ['Bezpłatny audyt','Automatyzacja','System rezerwacji','Agent AI','Inne'];

  const today = React.useMemo(() => { const d = new Date(); d.setHours(0,0,0,0); return d; }, []);

  const [step, setStep] = React.useState(0);            // 0 kalendarz, 1 formularz, 2 podziękowanie
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [month, setMonth] = React.useState(() => new Date(today.getFullYear(), today.getMonth(), 1));
  const [form, setForm] = React.useState({ name:'', email:'', company:'', topic:'', notes:'', _hp:'' });

  // dostępność z backendu
  const [availability, setAvailability] = React.useState({}); // { 'YYYY-MM-DD': ['10:30', ...] }
  const [loadState, setLoadState] = React.useState('idle');   // 'idle'|'loading'|'ok'|'error'
  const [meetLink, setMeetLink] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [bookingError, setBookingError] = React.useState(null); // 'slot_taken'|'error'|null

  React.useEffect(() => { if (window.lucide) lucide.createIcons(); });

  // helpers
  const pad = (n) => String(n).padStart(2,'0');
  const fmtKey = (d) => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
  const monthKey = (mDate) => `${mDate.getFullYear()}-${pad(mDate.getMonth()+1)}`;
  const fmtPrettyDate = (d) => `${DOW_PL_FULL[d.getDay()]}, ${d.getDate()} ${MONTHS_PL_DM[d.getMonth()]} ${d.getFullYear()}`;

  // pobierz dostępność dla widocznego miesiąca
  const loadMonth = React.useCallback((mDate) => {
    if (!window.BookingAPI) { setLoadState('error'); return; }
    setLoadState('loading');
    window.BookingAPI.fetchAvailability(monthKey(mDate))
      .then((res) => { setAvailability((res && res.days) || {}); setLoadState('ok'); })
      .catch(() => { setLoadState('error'); });
  }, []);

  React.useEffect(() => { loadMonth(month); }, [month, loadMonth]);

  const slotsForKey = (key) => availability[key] || [];

  const daysGrid = React.useMemo(() => {
    const year = month.getFullYear(), m = month.getMonth();
    const offset = (new Date(year, m, 1).getDay() + 6) % 7;
    const daysInMonth = new Date(year, m + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < offset; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(year, m, d));
    return cells;
  }, [month]);

  const monthIsCurrent = month.getFullYear() === today.getFullYear() && month.getMonth() === today.getMonth();
  const prevMonth = () => {
    const prev = new Date(month.getFullYear(), month.getMonth() - 1, 1);
    if (prev < new Date(today.getFullYear(), today.getMonth(), 1)) return;
    setMonth(prev);
  };
  const nextMonth = () => setMonth(new Date(month.getFullYear(), month.getMonth() + 1, 1));

  const selectedDateObj = date ? new Date(date) : null;
  const slots = date ? slotsForKey(date) : [];

  const pickDate = (d) => { setDate(fmtKey(d)); setTime(null); };
  const pickTime = (t) => { setTime(t); setBookingError(null); setStep(1); };
  const goBackToCal = () => setStep(0);

  const submit = (e) => {
    if (e) e.preventDefault();
    if (submitting) return;
    setBookingError(null);
    setSubmitting(true);
    const payload = { date, time, name: form.name, email: form.email, company: form.company, topic: form.topic, notes: form.notes, _hp: form._hp };
    window.BookingAPI.createBooking(payload)
      .then((res) => { setMeetLink((res && res.meetLink) || null); setStep(2); })
      .catch((err) => {
        if (err && err.reason === 'slot_taken') {
          setBookingError('slot_taken');
          setStep(0);
          setTime(null);
          loadMonth(month); // odśwież — slot mógł zniknąć
        } else {
          setBookingError('error');
        }
      })
      .finally(() => setSubmitting(false));
  };

  const restart = () => {
    setStep(0); setDate(null); setTime(null); setMeetLink(null); setBookingError(null);
    setForm({ name:'', email:'', company:'', topic:'', notes:'', _hp:'' });
    loadMonth(month);
  };

  const canSubmit = form.name.trim() && form.email.trim() && form.company.trim() && form.topic && !submitting;

  // ── renderery ──
  const renderProgress = () => (
    <div className="cc-progress" aria-label="Postęp">
      <span className={'cc-progress-step' + (step > 0 ? ' is-done' : ' is-active')}>
        {step > 0 ? <span key="d1" className="cc-progress-ico"><i data-lucide="check"></i></span> : <span key="n1">01</span>}
      </span>
      <span className="cc-progress-dash"></span>
      <span className={'cc-progress-step' + (step > 1 ? ' is-done' : step === 1 ? ' is-active' : '')}>
        {step > 1 ? <span key="d2" className="cc-progress-ico"><i data-lucide="check"></i></span> : <span key="n2">02</span>}
      </span>
      <span className="cc-progress-dash"></span>
      <span className={'cc-progress-step' + (step === 2 ? ' is-active' : '')}>03</span>
    </div>
  );

  const renderCalendar = () => (
    <>
      <div className="cc-cal-toolbar">
        <div className="cc-cal-month">{MONTHS_PL[month.getMonth()]} {month.getFullYear()}</div>
        <div className="cc-cal-nav">
          <button type="button" onClick={prevMonth} disabled={monthIsCurrent} aria-label="Poprzedni miesiąc"><i data-lucide="chevron-left"></i></button>
          <button type="button" onClick={nextMonth} aria-label="Następny miesiąc"><i data-lucide="chevron-right"></i></button>
        </div>
      </div>

      {bookingError === 'slot_taken' && (
        <div className="cc-slots-empty" role="alert" style={{color:'var(--c-blue)'}}>
          Ten termin właśnie zniknął — wybierz inny.
        </div>
      )}
      {loadState === 'error' && (
        <div className="cc-slots-empty" role="alert">
          Nie udało się pobrać terminów. <button type="button" className="cc-summary-change" onClick={() => loadMonth(month)}>Spróbuj ponownie</button>
        </div>
      )}

      <div className="cc-cal-grid" aria-busy={loadState === 'loading'}>
        {DOW_PL.map((d) => <div key={d} className="cc-cal-dow">{d}</div>)}
        {daysGrid.map((d, i) => {
          if (!d) return <button key={'e'+i} type="button" className="cc-cal-day is-empty" tabIndex={-1}></button>;
          const key = fmtKey(d);
          const isPast = d < today;
          const hasSlots = (availability[key] || []).length > 0;
          const isToday = key === fmtKey(today);
          const isSel = key === date;
          const disabled = isPast || !hasSlots || loadState !== 'ok';
          return (
            <button key={key} type="button"
              className={'cc-cal-day' + (isToday ? ' is-today' : '') + (isSel ? ' is-selected' : '')}
              disabled={disabled} onClick={() => pickDate(d)}
              aria-label={d.getDate() + ' ' + MONTHS_PL[d.getMonth()]}>
              {d.getDate()}
            </button>
          );
        })}
      </div>

      <div className="cc-slots-head">
        <div className="cc-slots-title">{selectedDateObj ? 'Godzina' : (loadState === 'loading' ? 'Ładowanie…' : 'Wybierz datę')}</div>
        <div className="cc-slots-meta">
          {selectedDateObj ? `${DOW_PL_FULL[selectedDateObj.getDay()]}, ${selectedDateObj.getDate()} ${MONTHS_PL_DM[selectedDateObj.getMonth()]}` : ''}
        </div>
      </div>

      <div className="cc-slots">
        {loadState === 'loading' && <div className="cc-slots-empty">Pobieram dostępne terminy…</div>}
        {loadState === 'ok' && !selectedDateObj && <div className="cc-slots-empty">Po wybraniu daty pojawią się dostępne godziny.</div>}
        {loadState === 'ok' && selectedDateObj && slots.length === 0 && <div className="cc-slots-empty">Brak dostępnych godzin w wybranym dniu.</div>}
        {loadState === 'ok' && selectedDateObj && slots.map((t) => (
          <button key={t} type="button" className="cc-slot" onClick={() => pickTime(t)}>{t}</button>
        ))}
      </div>
    </>
  );

  const renderForm = () => (
    <>
      <div className="cc-summary">
        <div className="cc-summary-left">
          <i data-lucide="calendar-check"></i>
          <span>{fmtPrettyDate(selectedDateObj)} · godz. {time}</span>
        </div>
        <button type="button" className="cc-summary-change" onClick={goBackToCal}>Zmień termin</button>
      </div>

      <form className="cc-form" onSubmit={submit}>
        <div className="cc-form-fields">
          <div className="cc-field cc-field--wide">
            <label className="cc-field-lbl" htmlFor="cc-name">Imię i nazwisko<span>*</span></label>
            <input id="cc-name" type="text" required value={form.name}
                   onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder="Anna Nowak" />
          </div>
          <div className="cc-field">
            <label className="cc-field-lbl" htmlFor="cc-email">Email<span>*</span></label>
            <input id="cc-email" type="email" required value={form.email}
                   onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} placeholder="anna@firma.pl" />
          </div>
          <div className="cc-field">
            <label className="cc-field-lbl" htmlFor="cc-company">Nazwa firmy<span>*</span></label>
            <input id="cc-company" type="text" required value={form.company}
                   onChange={(e) => setForm((f) => ({ ...f, company: e.target.value }))} placeholder="Firma sp. z o.o." />
          </div>
          <div className="cc-field cc-field--wide">
            <label className="cc-field-lbl" htmlFor="cc-topic">O czym chcesz porozmawiać?<span>*</span></label>
            <select id="cc-topic" required value={form.topic}
                    onChange={(e) => setForm((f) => ({ ...f, topic: e.target.value }))}>
              <option value="" disabled>Wybierz temat rozmowy…</option>
              {TOPICS.map((t) => <option key={t} value={t}>{t}</option>)}
            </select>
          </div>
          <div className="cc-field cc-field--wide">
            <label className="cc-field-lbl" htmlFor="cc-notes">Dodatkowe informacje (opcjonalnie)</label>
            <textarea id="cc-notes" value={form.notes}
                      onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
                      placeholder="Krótko o Twoim biznesie, problemie, oczekiwaniach…"></textarea>
          </div>
          {/* honeypot — ukryte pole; boty je wypełniają, ludzie nie */}
          <div aria-hidden="true" style={{position:'absolute', left:'-9999px', width:1, height:1, overflow:'hidden'}}>
            <label htmlFor="cc-hp">Nie wypełniaj tego pola</label>
            <input id="cc-hp" type="text" tabIndex={-1} autoComplete="off" value={form._hp}
                   onChange={(e) => setForm((f) => ({ ...f, _hp: e.target.value }))} />
          </div>
        </div>

        {bookingError === 'error' && (
          <p className="cc-fine" role="alert" style={{color:'#b3261e'}}>Nie udało się zarezerwować. Spróbuj ponownie za chwilę.</p>
        )}

        <div className="cc-form-actions">
          <button type="button" className="cc-btn cc-btn--ghost" onClick={goBackToCal}><i data-lucide="arrow-left"></i> Wstecz</button>
          <button key={submitting ? 'sub-sending' : 'sub-idle'} type="submit" className="cc-btn cc-btn--primary" disabled={!canSubmit}>
            {submitting ? 'Rezerwuję…' : <>Umów rozmowę <i data-lucide="arrow-right"></i></>}
          </button>
        </div>

        <p className="cc-fine">Pola oznaczone <span style={{color:'var(--c-blue)'}}>*</span> są wymagane.</p>
      </form>
    </>
  );

  const renderThanks = () => (
    <div className="cc-thanks">
      <div className="cc-thanks-mark"><i data-lucide="check"></i></div>
      <h3 className="cc-thanks-title">Termin <em>zarezerwowany</em></h3>
      <p className="cc-thanks-msg">
        Wysłałem Ci zaproszenie na maila{meetLink ? ' z linkiem do spotkania' : ''}. Do zobaczenia!
      </p>

      <dl className="cc-thanks-card">
        <dt>Termin</dt><dd>{fmtPrettyDate(selectedDateObj)} · godz. {time}</dd>
        <dt>Temat</dt><dd>{form.topic}</dd>
        <dt>Kontakt</dt><dd>{form.name} · {form.email}</dd>
        {meetLink && <><dt>Spotkanie</dt><dd><a href={meetLink} target="_blank" rel="noopener noreferrer">{meetLink}</a></dd></>}
      </dl>

      <button type="button" className="cc-btn cc-btn--ghost" onClick={restart} style={{marginTop: 18}}>
        <i data-lucide="rotate-ccw"></i> Umów kolejną rozmowę
      </button>
    </div>
  );

  return (
    <div className="cc-widget" aria-label="Umów rozmowę">
      <div className="cc-head">
        <span className="cc-head-title"><i data-lucide="calendar-days"></i> Umów rozmowę</span>
        {renderProgress()}
      </div>
      <div className="cc-body" key={'step-' + step}>
        {step === 0 && renderCalendar()}
        {step === 1 && renderForm()}
        {step === 2 && renderThanks()}
      </div>
    </div>
  );
}

function ContactDeezer() {
  React.useEffect(() => { if (window.lucide) lucide.createIcons(); });
  return (
    <section className="g-contact-section" id="kontakt">
      <div className="g-contact-inner">
        <div className="g-contact-left">
          <h2 className="g-contact-title">
            Umów <em>bezpłatny</em> audyt.
          </h2>
          <p className="g-contact-lead">
            30 minut, w których poznaję Twój biznes i mówię wprost, jak mogę Ci pomóc.
          </p>
          <div className="g-contact-bullets">
            <div className="g-contact-bullets-label">W ciągu 30 minut:</div>
            <ul>
              <li>Poznam Twoje procesy i zobaczę, co dziś zjada Twoją marżę albo czas.</li>
              <li>Sprawdzimy razem, gdzie automatyzacja albo AI mają sens - a gdzie tylko skomplikują sprawę.</li>
              <li>Powiem Ci wprost, czy realnie mogę Ci pomóc - jeśli nie, oszczędzę Twój czas.</li>
              <li>Wyjdziesz z konkretnym następnym krokiem.</li>
            </ul>
          </div>
          <div className="g-contact-direct">
            <div className="g-contact-row">
              <i data-lucide="mail"></i>
              <div>
                <div className="g-contact-lbl">Mail</div>
                <div className="g-contact-val">kontakt@maciejmatera.pl</div>
              </div>
            </div>
          </div>
        </div>

        <ContactCalendar />
      </div>
    </section>
  );
}

window.ContactCalendar = ContactCalendar;
window.ContactDeezer = ContactDeezer;
