// Workshop landing — shared components.

const Icon = ({ name, size = 24, stroke = 1.75, ...rest }) => {
  const paths = {
    'check': <path d="M5 12l4 4 10-10"/>,
    'check-thin': <path d="M5 12l4 4 10-10"/>,
    'arrow-right': <><path d="M5 12h14"/><path d="M13 5l7 7-7 7"/></>,
    'chevron-down': <path d="M6 9l6 6 6-6"/>,
    'play': <path d="M6 4l14 8-14 8z"/>,
    'mail': <><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 7l10 7 10-7"/></>,
    'file-edit': <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h8"/><path d="M14 2v6h6"/><path d="M14 2l6 6"/><path d="M18 14l4 4-4 4"/><path d="M22 18h-8"/></>,
    'file-text': <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M9 13h6M9 17h4"/></>,
    'sparkles': <><path d="M12 3l1.7 4.3L18 9l-4.3 1.7L12 15l-1.7-4.3L6 9l4.3-1.7z"/><path d="M19 15l.8 2 2 .8-2 .8L19 21l-.8-2-2-.8 2-.8z"/></>,
    'message': <><path d="M21 11a8 8 0 0 1-8 8H8l-5 3V11a8 8 0 0 1 8-8h2a8 8 0 0 1 8 8z"/></>,
    'pen': <><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"/></>,
    'calendar': <><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></>,
    'compass': <><circle cx="12" cy="12" r="10"/><path d="M16.24 7.76l-2.83 7.07-7.07 2.83 2.83-7.07z"/></>,
    'lightbulb': <><path d="M9 18h6"/><path d="M10 22h4"/><path d="M12 2a7 7 0 0 0-4 12.7c.7.7 1 1.5 1 2.3v1h6v-1c0-.8.3-1.6 1-2.3A7 7 0 0 0 12 2z"/></>,
    'user': <><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></>,
    'user-circle': <><circle cx="12" cy="12" r="10"/><circle cx="12" cy="10" r="3.2"/><path d="M6 19a6 6 0 0 1 12 0"/></>,
    'star': <path d="M12 2l3 7h7l-5.5 4.5 2 7L12 16l-6.5 4.5 2-7L2 9h7z"/>,
    'clock': <><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></>,
    'shield': <><path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6z"/><path d="M9 12l2 2 4-4"/></>,
    'list-checks': <><path d="M3 6h2v2H3zM3 11h2v2H3zM3 16h2v2H3z"/><path d="M9 7h12M9 12h12M9 17h12"/></>,
    'inbox': <><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.5 5h13l3 7v6a2 2 0 0 1-2 2h-15a2 2 0 0 1-2-2v-6z"/></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" {...rest}>
      {paths[name] || null}
    </svg>
  );
};

const Reveal = ({ children, delay = 0, as: As = 'div', className = '', ...rest }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    // Trigger when ~20% of the element is in view and only after it crosses
    // the viewport bottom by ~12%. Stops sections from already being "done"
    // by the time the user actually scrolls into them.
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && e.intersectionRatio >= 0.18) {
          setTimeout(() => el.classList.add('is-visible'), delay);
          io.unobserve(el);
        }
      });
    }, { threshold: [0, 0.18, 0.35], rootMargin: '0px 0px -12% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <As ref={ref} className={`reveal ${className}`} {...rest}>{children}</As>;
};

const scrollToForm = () => {
  const el = document.getElementById('reg-form');
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 24;
  window.scrollTo({ top, behavior: 'smooth' });
};

const SESSIONS = [
  { id: 'thu-4-jun', label: 'Thursday 4 June, 1:00pm UK time', day: 'Thu', date: '04 Jun', month: 'Jun',
    when: 'Thursday 4 June',     time: '1:00pm UK time',
    startUTC: '20260604T120000Z', endUTC: '20260604T124500Z' },
  { id: 'tue-9-jun', label: 'Tuesday 9 June, 6:00pm UK time',  day: 'Tue', date: '09 Jun', month: 'Jun',
    when: 'Tuesday 9 June',      time: '6:00pm UK time',
    startUTC: '20260609T170000Z', endUTC: '20260609T174500Z' },
];

// Calendar helpers — build Google + .ics for a session
const calTitle = 'The Smart Business System · Free AI workshop';
const calDetails = 'How to use AI to get through the work that slows you down. A practical workshop with The Smart Business System.';
const calLocation = 'Online (Zoom)';
function googleCalUrl(s) {
  const params = new URLSearchParams({
    action: 'TEMPLATE',
    text: calTitle,
    dates: `${s.startUTC}/${s.endUTC}`,
    details: calDetails,
    location: calLocation,
  });
  return `https://calendar.google.com/calendar/render?${params.toString()}`;
}
function outlookCalUrl(s) {
  // Outlook expects ISO-style timestamps
  const iso = (utc) => `${utc.slice(0,4)}-${utc.slice(4,6)}-${utc.slice(6,8)}T${utc.slice(9,11)}:${utc.slice(11,13)}:${utc.slice(13,15)}+00:00`;
  const params = new URLSearchParams({
    path: '/calendar/action/compose',
    rru: 'addevent',
    subject: calTitle,
    body: calDetails,
    location: calLocation,
    startdt: iso(s.startUTC),
    enddt: iso(s.endUTC),
  });
  return `https://outlook.live.com/calendar/0/deeplink/compose?${params.toString()}`;
}
function office365CalUrl(s) {
  const iso = (utc) => `${utc.slice(0,4)}-${utc.slice(4,6)}-${utc.slice(6,8)}T${utc.slice(9,11)}:${utc.slice(11,13)}:${utc.slice(13,15)}+00:00`;
  const params = new URLSearchParams({
    path: '/calendar/action/compose',
    rru: 'addevent',
    subject: calTitle,
    body: calDetails,
    location: calLocation,
    startdt: iso(s.startUTC),
    enddt: iso(s.endUTC),
  });
  return `https://outlook.office.com/calendar/0/deeplink/compose?${params.toString()}`;
}
function yahooCalUrl(s) {
  // Yahoo uses YYYYMMDDTHHmmssZ format, which matches our existing UTC format
  const params = new URLSearchParams({
    v: '60',
    title: calTitle,
    st: s.startUTC,
    et: s.endUTC,
    desc: calDetails,
    in_loc: calLocation,
  });
  return `https://calendar.yahoo.com/?${params.toString()}`;
}
function icsBlobUrl(s) {
  const stamp = s.startUTC;
  const ics = [
    'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//SBS//Workshop//EN',
    'CALSCALE:GREGORIAN', 'METHOD:PUBLISH',
    'BEGIN:VEVENT',
    `UID:${s.id}-${stamp}@smartbusinesssystem`,
    `DTSTAMP:${stamp}`,
    `DTSTART:${s.startUTC}`,
    `DTEND:${s.endUTC}`,
    `SUMMARY:${calTitle}`,
    `DESCRIPTION:${calDetails}`,
    `LOCATION:${calLocation}`,
    'END:VEVENT', 'END:VCALENDAR',
  ].join('\r\n');
  return URL.createObjectURL(new Blob([ics], { type: 'text/calendar' }));
}

// Workshop landing — shared components.
// Premium form card design — clean white card on dark hero, teal CTA.

const RegForm = () => {
  const [first, setFirst] = React.useState('');
  const [last, setLast] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [session, setSession] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [interacted, setInteracted] = React.useState(false);

  // Idle pulse — apply the .is-idle class continuously until the user touches
  // a field. The 6s loop is driven by CSS so the pulse window is reached
  // naturally; we just toggle the class on/off based on interaction state.
  const idle = !interacted;
  const onInteract = () => { if (!interacted) setInteracted(true); };

  const submit = (e) => {
    e.preventDefault();
    if (!first.trim() || !last.trim() || !email.trim() || !session) return;
    const s = SESSIONS.find(x => x.id === session);
    const payload = {
      first_name: first.trim(),
      last_name: last.trim(),
      email: email.trim().toLowerCase(),
      session_id: s.id,
      session_when: s.when,
      session_time: s.time,
      session_start_utc: s.startUTC,
      source: 'the14hourfix-landing',
      page_url: window.location.href,
    };
    // Post to our own serverless function, which forwards server-to-server
    // to Zoho Flow with the proper Content-Type. Same-origin so no CORS;
    // browser receives a real response so we can surface failures.
    try {
      fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
        keepalive: true,
      }).catch(() => {});
    } catch (_) { /* noop */ }
    setDone(true);
  };

  const selectedSession = SESSIONS.find(s => s.id === session);

  if (done) {
    return (
      <div className="reg-wrap" id="reg-form">
        <div className="form-card">
          <div className="form-success">
            <div className="tick"><Icon name="check" size={28} stroke={2.5}/></div>
            <h3>You&rsquo;re in, {first.split(' ')[0]}.</h3>
            <p>Check your inbox for joining details. Add the workshop to your calendar so you don&rsquo;t miss it.</p>
            {selectedSession && (
              <div className="calendar-buttons">
                <a className="calendar-btn" href={googleCalUrl(selectedSession)} target="_blank" rel="noopener noreferrer">
                  <span className="icn"><Icon name="calendar" size={16} stroke={1.85}/></span>
                  Google Calendar
                </a>
                <a className="calendar-btn" href={outlookCalUrl(selectedSession)} target="_blank" rel="noopener noreferrer">
                  <span className="icn"><Icon name="calendar" size={16} stroke={1.85}/></span>
                  Outlook.com
                </a>
                <a className="calendar-btn" href={office365CalUrl(selectedSession)} target="_blank" rel="noopener noreferrer">
                  <span className="icn"><Icon name="calendar" size={16} stroke={1.85}/></span>
                  Office 365
                </a>
                <a className="calendar-btn" href={yahooCalUrl(selectedSession)} target="_blank" rel="noopener noreferrer">
                  <span className="icn"><Icon name="calendar" size={16} stroke={1.85}/></span>
                  Yahoo Calendar
                </a>
                <a className="calendar-btn" href={icsBlobUrl(selectedSession)} download="sbs-workshop.ics">
                  <span className="icn"><Icon name="calendar" size={16} stroke={1.85}/></span>
                  Apple Calendar (.ics)
                </a>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="reg-wrap" id="reg-form">
      <div className="form-card">
        <div className="form-card-head">
          <h3>Save your free place</h3>
          <p>Choose your live session and we&rsquo;ll send the details to your inbox.</p>
        </div>
        <form className="form-card-body" onSubmit={submit} onFocus={onInteract} onClick={onInteract}>
          <div className="form-stack">
            <div className="field-row">
              <div className="field">
                <label className="field-label" htmlFor="first">First name<span className="req">*</span></label>
                <input id="first" className="field-input" required value={first} onChange={(e) => setFirst(e.target.value)} autoComplete="given-name"/>
              </div>
              <div className="field">
                <label className="field-label" htmlFor="last">Last name<span className="req">*</span></label>
                <input id="last" className="field-input" required value={last} onChange={(e) => setLast(e.target.value)} autoComplete="family-name"/>
              </div>
            </div>
            <div className="field">
              <label className="field-label" htmlFor="email">Email<span className="req">*</span></label>
              <input id="email" type="email" className="field-input" required value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email"/>
            </div>
            <div className="field">
              <label className="field-label" htmlFor="session">Select your session<span className="req">*</span></label>
              <select id="session" className="field-select" required value={session} onChange={(e) => setSession(e.target.value)}>
                <option value="">Choose a session...</option>
                {SESSIONS.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            </div>
            {selectedSession && (
              <div className="session-preview" role="status">
                <span className="icn"><Icon name="calendar" size={16} stroke={1.85}/></span>
                <span><span className="pill-label">Reminder set for</span> {selectedSession.when}, {selectedSession.time}</span>
              </div>
            )}
            <button type="submit" className={`btn btn-primary btn-lg btn-block ${idle ? 'is-idle' : ''}`} style={{ marginTop: 6 }}>
              Save my free place <Icon name="arrow-right" size={18} stroke={2.25}/>
            </button>
          </div>
        </form>
      </div>
      <p className="form-disclaimer">
        By registering, you agree that we&rsquo;ll send you emails about this workshop, including reminders, the joining link and the recording. You can unsubscribe from future updates at any time.
      </p>
    </div>
  );
};

const FloatingCTA = () => {
  const [shown, setShown] = React.useState(false);
  const [hidden, setHidden] = React.useState(false);
  React.useEffect(() => {
    const handler = () => {
      const hero = document.getElementById('hero');
      const final = document.getElementById('final-cta');
      const form = document.getElementById('reg-form');
      if (!hero) return;
      const heroBottom = hero.getBoundingClientRect().bottom;
      const finalTop = final ? final.getBoundingClientRect().top : Infinity;
      const vh = window.innerHeight;
      setShown(heroBottom < 60 && finalTop > vh * 0.85);
      // Hide if the form is in view (so it doesn't cover form fields)
      if (form) {
        const fr = form.getBoundingClientRect();
        const formInView = fr.top < vh * 0.9 && fr.bottom > vh * 0.2;
        setHidden(formInView);
      }
    };
    handler();
    window.addEventListener('scroll', handler, { passive: true });
    window.addEventListener('resize', handler);
    return () => { window.removeEventListener('scroll', handler); window.removeEventListener('resize', handler); };
  }, []);
  return (
    <button
      className={`float-cta ${shown ? 'is-shown' : ''} ${hidden ? 'is-hidden' : ''}`}
      onClick={scrollToForm}
      aria-label="Save my free place"
    >
      <span className="label-desktop">
        <span>Save my free place, register now</span>
        <Icon name="arrow-right" size={14} stroke={2.5}/>
      </span>
      <span className="label-mobile">
        <span>Save my free place, register now</span>
        <Icon name="arrow-right" size={16} stroke={2.5}/>
      </span>
    </button>
  );
};

Object.assign(window, { Icon, Reveal, RegForm, FloatingCTA, scrollToForm, SESSIONS });
