// Interactive Cal.com-style scheduler component
const { useState, useMemo, useEffect } = React;

const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const DAYS_SHORT = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const DAYS_MINI = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];

// Generate 45-min slots, 9am-5pm, weekdays only, skip lunch
const TIME_SLOTS = [
  '9:00 AM', '9:45 AM', '10:30 AM', '11:15 AM',
  '1:00 PM', '1:45 PM', '2:30 PM', '3:15 PM', '4:00 PM'
];

function formatLongDate(d) {
  return `${DAYS_SHORT[d.getDay()]}, ${MONTHS[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
}

function isSameDay(a, b) {
  return a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

function isBookable(date, today) {
  if (!date) return false;
  const d = new Date(date); d.setHours(0,0,0,0);
  const t = new Date(today); t.setHours(0,0,0,0);
  if (d < t) return false;
  // No weekends
  if (d.getDay() === 0 || d.getDay() === 6) return false;
  // Only within next 60 days
  const diff = (d - t) / (1000*60*60*24);
  if (diff > 60) return false;
  return true;
}

function MonthGrid({ viewMonth, setViewMonth, selectedDate, setSelectedDate, today, accent }) {
  const firstOfMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth(), 1);
  const startWeekday = firstOfMonth.getDay();
  const daysInMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth() + 1, 0).getDate();

  const cells = [];
  for (let i = 0; i < startWeekday; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(viewMonth.getFullYear(), viewMonth.getMonth(), d));
  while (cells.length % 7 !== 0) cells.push(null);

  const prev = () => {
    const n = new Date(viewMonth); n.setMonth(n.getMonth() - 1);
    if (n.getFullYear() < today.getFullYear() || (n.getFullYear() === today.getFullYear() && n.getMonth() < today.getMonth())) return;
    setViewMonth(n);
  };
  const next = () => {
    const n = new Date(viewMonth); n.setMonth(n.getMonth() + 1);
    setViewMonth(n);
  };

  const canGoBack = !(viewMonth.getFullYear() === today.getFullYear() && viewMonth.getMonth() === today.getMonth());

  return (
    <div className="cal-month">
      <div className="cal-month-header">
        <div className="cal-month-title">{MONTHS[viewMonth.getMonth()]} {viewMonth.getFullYear()}</div>
        <div className="cal-month-nav">
          <button onClick={prev} disabled={!canGoBack} aria-label="Previous month">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="15 18 9 12 15 6"></polyline></svg>
          </button>
          <button onClick={next} aria-label="Next month">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="9 18 15 12 9 6" transform="rotate(180 12 12)"></polyline></svg>
          </button>
        </div>
      </div>
      <div className="cal-weekdays">
        {DAYS_MINI.map((d, i) => <div key={i}>{d}</div>)}
      </div>
      <div className="cal-grid">
        {cells.map((c, i) => {
          if (!c) return <div key={i} className="cal-cell empty" />;
          const bookable = isBookable(c, today);
          const selected = isSameDay(c, selectedDate);
          const isToday = isSameDay(c, today);
          return (
            <button
              key={i}
              className={`cal-cell ${bookable ? 'bookable' : 'disabled'} ${selected ? 'selected' : ''} ${isToday ? 'today' : ''}`}
              disabled={!bookable}
              onClick={() => setSelectedDate(c)}
            >
              {c.getDate()}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function DateStrip({ selectedDate, setSelectedDate, today }) {
  const [offset, setOffset] = useState(0);
  const days = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 14; i++) {
      const d = new Date(today);
      d.setDate(d.getDate() + offset + i);
      arr.push(d);
    }
    return arr;
  }, [offset, today]);

  return (
    <div className="cal-strip">
      <div className="cal-strip-header">
        <div className="cal-strip-title">Select a day</div>
        <div className="cal-strip-nav">
          <button onClick={() => setOffset(Math.max(0, offset - 7))} disabled={offset === 0}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="15 18 9 12 15 6"></polyline></svg>
          </button>
          <button onClick={() => setOffset(offset + 7)}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="9 6 15 12 9 18"></polyline></svg>
          </button>
        </div>
      </div>
      <div className="cal-strip-days">
        {days.map((d, i) => {
          const bookable = isBookable(d, today);
          const selected = isSameDay(d, selectedDate);
          return (
            <button
              key={i}
              className={`cal-strip-day ${bookable ? 'bookable' : 'disabled'} ${selected ? 'selected' : ''}`}
              disabled={!bookable}
              onClick={() => setSelectedDate(d)}
            >
              <div className="cal-strip-dow">{DAYS_SHORT[d.getDay()].slice(0,3)}</div>
              <div className="cal-strip-num">{d.getDate()}</div>
              <div className="cal-strip-mo">{MONTHS[d.getMonth()].slice(0,3)}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function TimeColumn({ selectedDate, selectedTime, setSelectedTime, onContinue }) {
  if (!selectedDate) {
    return (
      <div className="cal-times empty-state">
        <div className="empty-icon">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
            <line x1="16" y1="2" x2="16" y2="6"></line>
            <line x1="8" y1="2" x2="8" y2="6"></line>
            <line x1="3" y1="10" x2="21" y2="10"></line>
          </svg>
        </div>
        <div className="empty-title">Pick a date</div>
        <div className="empty-sub">Available times will appear here</div>
      </div>
    );
  }
  return (
    <div className="cal-times">
      <div className="cal-times-header">
        <div className="cal-times-date">{formatLongDate(selectedDate)}</div>
        <div className="cal-times-sub">Eastern Time (UTC−5)</div>
      </div>
      <div className="cal-times-list">
        {TIME_SLOTS.map((t, i) => {
          const isSelected = selectedTime === t;
          return (
            <div key={i} className={`cal-time-row ${isSelected ? 'selected' : ''}`}>
              <button
                className="cal-time-main"
                onClick={() => setSelectedTime(t)}
              >
                {t}
              </button>
              {isSelected && (
                <button className="cal-time-next" onClick={onContinue}>
                  Next →
                </button>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function BookingForm({ selectedDate, selectedTime, onBack, onConfirm }) {
  const [form, setForm] = useState({
    firstName: '', lastName: '', email: '', phone: '',
    brokerage: '', agents: '10-25', province: 'Ontario', current: '',
    notes: ''
  });
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const canSubmit = form.firstName && form.lastName && form.email && form.brokerage;

  return (
    <div className="cal-form">
      <div className="cal-form-summary">
        <button className="cal-form-back" onClick={onBack}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="15 18 9 12 15 6"></polyline></svg>
          Back
        </button>
        <div className="cal-form-meta">
          <div className="cal-form-meta-row">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
            {formatLongDate(selectedDate)}
          </div>
          <div className="cal-form-meta-row">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            {selectedTime} · 45 minutes
          </div>
          <div className="cal-form-meta-row">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 10l5 5-5 5"/><path d="M4 4v7a4 4 0 0 0 4 4h12"/></svg>
            Google Meet (link sent on confirm)
          </div>
        </div>
      </div>
      <div className="cal-form-fields">
        <div className="cal-form-row two">
          <label>
            <span>First name *</span>
            <input value={form.firstName} onChange={e => update('firstName', e.target.value)} placeholder="Alex" />
          </label>
          <label>
            <span>Last name *</span>
            <input value={form.lastName} onChange={e => update('lastName', e.target.value)} placeholder="Tremblay" />
          </label>
        </div>
        <div className="cal-form-row two">
          <label>
            <span>Work email *</span>
            <input type="email" value={form.email} onChange={e => update('email', e.target.value)} placeholder="alex@brokerage.ca" />
          </label>
          <label>
            <span>Phone</span>
            <input value={form.phone} onChange={e => update('phone', e.target.value)} placeholder="(416) 555-0199" />
          </label>
        </div>
        <div className="cal-form-row two">
          <label>
            <span>Brokerage name *</span>
            <input value={form.brokerage} onChange={e => update('brokerage', e.target.value)} placeholder="Maple Realty Inc." />
          </label>
          <label>
            <span>Agents in your office</span>
            <select value={form.agents} onChange={e => update('agents', e.target.value)}>
              <option>Under 10</option>
              <option>10-25</option>
              <option>26-50</option>
              <option>50+</option>
            </select>
          </label>
        </div>
        <div className="cal-form-row two">
          <label>
            <span>Province</span>
            <select value={form.province} onChange={e => update('province', e.target.value)}>
              <option>Ontario</option>
              <option>Quebec</option>
              <option>British Columbia</option>
              <option>Alberta</option>
              <option>Manitoba</option>
              <option>Saskatchewan</option>
              <option>Nova Scotia</option>
              <option>New Brunswick</option>
              <option>Newfoundland and Labrador</option>
              <option>Prince Edward Island</option>
            </select>
          </label>
          <label>
            <span>Current software</span>
            <select value={form.current} onChange={e => update('current', e.target.value)}>
              <option value="">Select…</option>
              <option>LoneWolf</option>
              <option>Skyslope</option>
              <option>DotLoop</option>
              <option>Spreadsheets / paper</option>
              <option>Other</option>
              <option>None yet</option>
            </select>
          </label>
        </div>
        <label className="cal-form-row">
          <span>What are you hoping to solve? <em>(optional)</em></span>
          <textarea value={form.notes} onChange={e => update('notes', e.target.value)} placeholder="e.g. compliance pain, onboarding agents faster, consolidating apps…" rows="3" />
        </label>
        <div className="cal-form-consent">
          By booking, you agree to NexOne's privacy policy. We'll never share your data.
        </div>
        <button className="cal-form-submit" disabled={!canSubmit} onClick={() => onConfirm(form)}>
          Confirm 45-min walkthrough
        </button>
      </div>
    </div>
  );
}

function Confirmation({ selectedDate, selectedTime, form, onReset }) {
  return (
    <div className="cal-confirm">
      <div className="cal-confirm-badge">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
          <polyline points="20 6 9 17 4 12"></polyline>
        </svg>
      </div>
      <div className="cal-confirm-title">You're booked, {form.firstName}.</div>
      <div className="cal-confirm-sub">
        A calendar invite and Google Meet link are on their way to <strong>{form.email}</strong>.
      </div>
      <div className="cal-confirm-card">
        <div className="cal-confirm-row">
          <span className="k">Date</span>
          <span className="v">{formatLongDate(selectedDate)}</span>
        </div>
        <div className="cal-confirm-row">
          <span className="k">Time</span>
          <span className="v">{selectedTime} ET · 45 min</span>
        </div>
        <div className="cal-confirm-row">
          <span className="k">With</span>
          <span className="v">Sarah Bergeron · Senior Solutions Consultant</span>
        </div>
        <div className="cal-confirm-row">
          <span className="k">Brokerage</span>
          <span className="v">{form.brokerage}</span>
        </div>
      </div>
      <div className="cal-confirm-note">
        Need to reschedule? You can manage this booking from the confirmation email.
      </div>
      <a className="cal-confirm-next" href="/post-booking">View preparation steps →</a>
      <button className="cal-confirm-reset" onClick={onReset}>Book another time</button>
    </div>
  );
}

function Scheduler() {
  useEffect(() => {
    const existing = document.querySelector('script[data-hubspot-meetings-embed]');
    if (existing) return;

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://static.hsappstatic.net/MeetingsEmbed/ex/MeetingsEmbedCode.js';
    script.async = true;
    script.dataset.hubspotMeetingsEmbed = 'true';
    document.body.appendChild(script);
  }, []);

  return (
    <div className="scheduler card-shell hubspot-scheduler-shell">
      <div className="scheduler-brand">
        <div className="scheduler-logo">
          <NexoneMark />
          <div>
            <div className="scheduler-logo-title">NexOne for Brokerages</div>
            <div className="scheduler-logo-sub">Discovery call</div>
          </div>
        </div>
      </div>
      {/* Start of Meetings Embed Script */}
      <div
        className="meetings-iframe-container"
        data-src="https://meetings-na3.hubspot.com/nexone/discovery-call?embed=true"
      ></div>
      {/* End of Meetings Embed Script */}
    </div>
  );
}

function NexoneMark({ size = 'sm' }) {
  // NEX in ink, ONE in orange — match nexone.ca wordmark
  const h = size === 'lg' ? 26 : 20;
  return (
    <div className="nexone-mark" aria-label="NexOne">
      <svg height={h} viewBox="0 0 253 44" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M25.39 29.48L5.998.21H0v42.88h6.432V13.46l19.56 29.63h5.83V.21H25.39v29.27z" fill="var(--wordmark)"/>
        <path d="M52.305 36.59V24.445H70.81v-6.502H52.305V6.712h20.371l.944-6.502H45.326v42.884h28.728l-1.02-6.502H52.305z" fill="var(--wordmark)"/>
        <path d="M118.097 0h-7.375L101.064 16.19 91.35.21h-7.375l12.468 21.394-12.487 21.432h7.526l9.563-16.188 9.526 15.979h7.526l-12.487-21.432L118.097 0z" fill="var(--wordmark)"/>
        <path d="M206.184 29.48L186.812.21h-6.017v42.88h6.432V13.46l19.559 29.63h5.83V.21h-6.432v29.27z" fill="var(--accent)"/>
        <path d="M251.983 36.59H231.27V24.445h18.504v-6.502H231.27V6.712h20.354l.943-6.502h-28.274v42.884H253l-1.017-6.502z" fill="var(--accent)"/>
        <path d="M134.28.305L121.812 21.66 134.28 42.998h24.918L171.666 21.66 159.198.305H134.28zm3.679 35.924l-8.658-14.835 8.658-14.835h17.56l8.658 14.835-8.658 14.835h-17.56z" fill="var(--accent)"/>
      </svg>
    </div>
  );
}

Object.assign(window, { Scheduler, NexoneMark });
