// confirmation.jsx — booking confirmation screen. Cohesive with the
// booking flow + intro-pack checkout: same cream background, same Sora
// display face, same accent + sage palette.

const { useState: useStateCF, useEffect: useEffectCF } = React;

const CF_BREAKPOINT = 700;
function useCFMobile() {
  const [m, setM] = useStateCF(typeof window !== 'undefined' ? window.innerWidth < CF_BREAKPOINT : false);
  useEffectCF(() => {
    const onResize = () => setM(window.innerWidth < CF_BREAKPOINT);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return m;
}

function ConfirmationApp({ brandId = 'halcyon' }) {
  const baseBrand = window.BRANDS[brandId];
  const mobile = useCFMobile();

  // Studio settings (tweaks) panel — opt-in via window.CF_TWEAKS_ENABLED.
  const tweaksEnabled = typeof window !== 'undefined' && window.CF_TWEAKS_ENABLED;
  const defaults = (typeof window !== 'undefined' && window.CF_TWEAK_DEFAULTS) || {};
  const [t, setTweak] = (tweaksEnabled ? window.useTweaks(defaults) : [defaults, () => {}]);

  const brand = tweaksEnabled ? {
    ...baseBrand,
    accent:        t.accent     ?? baseBrand.accent,
    accentDeep:    t.accent     ?? baseBrand.accentDeep,
    accentSoft:    baseBrand.accentSoft,
    surface:       t.panel      ?? baseBrand.surface,
    border:        t.lineColor  ?? baseBrand.border,
    ink:           t.headline   ?? baseBrand.ink,
    inkSoft:       t.details    ?? baseBrand.inkSoft,
    displayFont:   t.font       ?? baseBrand.displayFont,
    bodyFont:      t.font       ?? baseBrand.bodyFont,
    displayWeight: t.weight     ?? baseBrand.displayWeight,
    _radius:       t.radius     ?? 12,
    _buttonTextColor: t.buttonTextColor,
  } : { ...baseBrand, _radius: 12 };
  const appBg = tweaksEnabled ? (t.background ?? '#FAFAF7') : '#FAFAF7';
  const hideCalendar    = !!t.hideCalendar;
  const hideBookAnother = !!t.hideBookAnother;
  const hideShare       = !!t.hideShare;
  const hideSetupAccount = !!t.hideSetupAccount;

  // Read the booking kind from the HTML wrapper. 'class' is the default,
  // 'appointment' renders the appointment-style confirmation.
  const kind = (typeof window !== 'undefined' && window.CF_KIND) || 'class';
  const isAppointment = kind === 'appointment';

  const headline = isAppointment ? "You're booked!" : "You're in!";
  const booking = isAppointment ? {
    title: 'Swedish Massage · 60 min with Yasmin',
    price: 120,
    date: 'Tue, May 14',
    time: '8:30 AM',
    provider: 'Yasmin Castillo',
    location: 'Halcyon Studio · 218 Atlantic Ave, Brooklyn',
    cardLast4: '4242',
    cardBrand: 'Visa',
    orderId: 'ZP-840293',
    email: 'jordan.reyes@gmail.com',
  } : {
    title: 'Reformer Flow with Marisol',
    price: 28,
    date: 'Tue, May 14',
    time: '8:30 AM',
    provider: 'Marisol Pena',
    location: 'Halcyon Studio · 218 Atlantic Ave, Brooklyn',
    cardLast4: '4242',
    cardBrand: 'Visa',
    orderId: 'ZP-840291',
    email: 'jordan.reyes@gmail.com',
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: appBg,
      fontFamily: brand.bodyFont,
      color: brand.ink,
      display: 'flex', justifyContent: 'center',
      padding: mobile ? '40px 18px 60px' : '64px 24px 60px',
    }}>
      <div style={{
        width: '100%',
        maxWidth: 640,
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Hero check + headline */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', marginBottom: 24 }}>
          <div style={{
            width: 64, height: 64, borderRadius: 999,
            background: brand.accent, color: '#fff',
            display: 'grid', placeItems: 'center',
            boxShadow: `0 0 0 8px ${brand.accentSoft}`,
            marginBottom: 18,
          }}>
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          </div>
          <h1 style={{
            fontFamily: brand.displayFont,
            fontWeight: brand.displayWeight,
            fontSize: mobile ? 30 : 40,
            lineHeight: 1.05,
            letterSpacing: '-0.02em',
            color: brand.ink,
            margin: 0,
          }}>{headline}</h1>
          <p style={{
            fontSize: 15, color: brand.inkSoft, lineHeight: 1.5,
            marginTop: 10, marginBottom: 0,
          }}>
            We sent a receipt to <strong style={{ color: brand.ink }}>{booking.email}</strong>.
          </p>
        </div>

        {/* Booking details card — minimal: title + price, two summary lines, receipt footer */}
        <div style={{
          background: '#fff',
          border: `1px solid ${brand.border}`,
          borderRadius: 14,
          padding: mobile ? '16px 18px 14px' : '20px 22px 16px',
          marginBottom: 14,
        }}>
          <div style={{
            display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
            gap: 12,
          }}>
            <div style={{
              fontFamily: brand.displayFont, fontWeight: brand.displayWeight,
              fontSize: mobile ? 17 : 20, color: brand.ink,
              letterSpacing: '-0.01em', lineHeight: 1.25,
            }}>{booking.title}</div>
            <div style={{
              fontFamily: brand.displayFont, fontWeight: 700,
              fontSize: mobile ? 17 : 20, color: brand.ink,
              flex: '0 0 auto',
            }}>${booking.price}</div>
          </div>

          <div style={{ marginTop: 8, fontSize: 13.5, color: brand.inkSoft, lineHeight: 1.55 }}>
            {booking.date} · {booking.time} with {booking.provider}<br/>
            {booking.location}
          </div>

          <div style={{
            marginTop: 14, paddingTop: 12,
            borderTop: `1px solid ${brand.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            gap: 12, flexWrap: 'wrap',
            fontSize: 12, color: brand.inkSoft,
          }}>
            <span>Charged to {booking.cardBrand} ····{booking.cardLast4}</span>
            <span>Order #{booking.orderId}</span>
          </div>
        </div>

        {/* Calendar buttons */}
        {!hideCalendar && (
          <div style={{
            display: 'grid',
            gridTemplateColumns: mobile ? '1fr 1fr 1fr' : '1fr 1fr 1fr',
            gap: 10,
            marginBottom: 10,
          }}>
            <CalendarButton brand={brand} label="Add to Google" iconColor="#4285F4" />
            <CalendarButton brand={brand} label="Add to Apple"  iconColor="#000000" />
            <CalendarButton brand={brand} label="Add to Outlook" iconColor="#0078D4" />
          </div>
        )}

        {/* Book another spot — class only. Lets you re-enter the flow to
            grab a second seat in the same class for a friend/family member. */}
        {!isAppointment && !hideBookAnother && (
          <button
            onClick={() => alert('Open booking flow with class pre-selected')}
            style={{
              width: '100%',
              background: brand.accentSoft,
              border: `1px solid ${brand.accent}`,
              borderRadius: 12,
              padding: '14px 18px',
              fontSize: 14, fontWeight: 600,
              color: brand.accentDeep,
              cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              marginBottom: 10,
            }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
              <circle cx="9" cy="7" r="4"/>
              <line x1="19" y1="8" x2="19" y2="14"/>
              <line x1="22" y1="11" x2="16" y2="11"/>
            </svg>
            Book another spot in this class for a friend or family member
          </button>
        )}

        {/* Share — class only on the appointment screen */}
        {!isAppointment && !hideShare && (
          <button
            onClick={() => alert('Share dialog')}
            style={{
              width: '100%',
              background: '#fff',
              border: `1px solid ${brand.border}`,
              borderRadius: 12,
              padding: '14px 18px',
              fontSize: 14, fontWeight: 600,
              color: brand.ink,
              cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              marginBottom: 22,
            }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={brand.inkSoft} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="18" cy="5" r="3"/>
              <circle cx="6" cy="12" r="3"/>
              <circle cx="18" cy="19" r="3"/>
              <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
              <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
            </svg>
            Share with someone
          </button>
        )}
        {isAppointment && <div style={{ height: 12 }} />}

        {/* Save info / set up account block */}
        {!hideSetupAccount && (
        <div style={{
          border: `1.5px dashed ${brand.accent}`,
          borderRadius: brand._radius ?? 14,
          padding: mobile ? '18px 18px 16px' : '22px 22px 18px',
          background: 'rgba(228, 236, 223, 0.35)',
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 10 }}>
            <div style={{
              flex: '0 0 auto', marginTop: 1,
              color: brand.accentDeep,
            }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <polygon points="12 2 15 9 22 9.5 17 14.5 18.5 22 12 18 5.5 22 7 14.5 2 9.5 9 9 12 2"/>
              </svg>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: brand.displayFont, fontWeight: 700,
                fontSize: 16, color: brand.ink, lineHeight: 1.3,
              }}>First time booking with us? Welcome!</div>
              <div style={{ fontSize: 13, color: brand.inkSoft, marginTop: 4, lineHeight: 1.5 }}>
                Save your info for next time. See your bookings, manage payments, and skip the forms.
              </div>
            </div>
          </div>
          <button
            onClick={() => alert('Setting up account…')}
            style={{
              width: '100%',
              background: brand.accent,
              color: '#fff',
              border: 0, borderRadius: 12,
              padding: '14px 18px',
              fontSize: 15, fontWeight: 700,
              fontFamily: brand.displayFont,
              letterSpacing: '-0.005em',
              cursor: 'pointer',
              boxShadow: `0 4px 14px ${brand.accentSoft}`,
              marginTop: 6,
            }}>
            Set up account
          </button>
        </div>
        )}
        <PoweredByZipper />
      </div>

      {tweaksEnabled && <CFTweaks t={t} setTweak={setTweak} />}
    </div>
  );
}

function DetailRowCF({ brand, icon, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
      <div style={{
        width: 30, height: 30, borderRadius: 8,
        background: brand.accentSoft, color: brand.accentDeep,
        display: 'grid', placeItems: 'center',
        flex: '0 0 auto',
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 11, fontWeight: 700,
          letterSpacing: '0.1em', textTransform: 'uppercase',
          color: brand.inkSoft, lineHeight: 1.4,
        }}>{label}</div>
        <div style={{
          fontSize: 14.5, color: brand.ink, marginTop: 2,
          lineHeight: 1.4, fontWeight: 600,
        }}>{value}</div>
      </div>
    </div>
  );
}

function CalendarButton({ brand, label, iconColor }) {
  return (
    <button
      onClick={() => alert(label)}
      style={{
        background: '#fff',
        border: `1px solid ${brand.border}`,
        borderRadius: 12,
        padding: '14px 10px',
        cursor: 'pointer',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
        fontSize: 13, fontWeight: 600,
        color: brand.ink,
      }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={iconColor} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2" ry="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>
      {label}
    </button>
  );
}

// ────────────────────────────────────────────────────────────────
// Studio settings panel — opt-in via window.CF_TWEAKS_ENABLED.
// ────────────────────────────────────────────────────────────────
function CFTweaks({ t, setTweak }) {
  const {
    TweaksPanel: Panel, TweakSection: Section, TweakColor: Color,
    TweakSlider: Slider, TweakSelect: Select, TweakToggle: Toggle,
    TweakButton: Button,
  } = window;
  const resetAll = () => {
    const defaults = (typeof window !== 'undefined' && window.CF_TWEAK_DEFAULTS) || {};
    Object.keys(defaults).forEach(k => setTweak(k, defaults[k]));
  };
  React.useEffect(() => {
    if (!Panel) return;
    const id = window.setTimeout(() => window.postMessage({ type: '__activate_edit_mode' }, '*'), 0);
    return () => window.clearTimeout(id);
  }, [Panel]);
  if (!Panel) return null;
  const FONTS = [
    "'Poppins', system-ui, sans-serif",
    "'Inter', system-ui, sans-serif",
    "'Sora', system-ui, sans-serif",
    "'Open Sans', system-ui, sans-serif",
    "'DM Sans', system-ui, sans-serif",
    "'Manrope', system-ui, sans-serif",
    "'Bebas Neue', sans-serif",
    "'Playfair Display', serif",
  ];
  const fontLabel = (f) => f.replace(/['"]/g, '').split(',')[0];
  return (
    <Panel title="Studio settings" noDeckControls={true}>
      <Section label="Surfaces" />
      <Color label="Accent"      value={t.accent}     onChange={(v) => setTweak('accent', v)} />
      <Color label="Background"  value={t.background} onChange={(v) => setTweak('background', v)} />
      <Color label="Panel"       value={t.panel}      onChange={(v) => setTweak('panel', v)} />
      <Color label="Line color"  value={t.lineColor || '#ECECEC'}
                                 onChange={(v) => setTweak('lineColor', v)} />

      <Section label="Text on background" />
      <Color label="Primary"     value={t.headline}   onChange={(v) => setTweak('headline', v)} />
      <Color label="Secondary"   value={t.details}    onChange={(v) => setTweak('details', v)} />

      <Section label="Text on accent" />
      <Color label="Button text" value={t.buttonTextColor || '#FFFFFF'}
                                 onChange={(v) => setTweak('buttonTextColor', v)} />

      <Section label="Typography" />
      <Select label="Font family" value={t.font}
              options={FONTS.map(f => ({ value: f, label: fontLabel(f) }))}
              onChange={(v) => setTweak('font', v)} />
      <Slider label="Headline weight" value={t.weight} min={300} max={800} step={100}
              onChange={(v) => setTweak('weight', v)} />

      <Section label="Shape" />
      <Slider label="Corner radius" value={t.radius} min={0} max={28} step={1} unit="px"
              onChange={(v) => setTweak('radius', v)} />

      <Section label="Hide" />
      <Toggle label="Calendar links"               value={!!t.hideCalendar}
              onChange={(v) => setTweak('hideCalendar', v)} />
      <Toggle label="Book another spot"            value={!!t.hideBookAnother}
              onChange={(v) => setTweak('hideBookAnother', v)} />
      <Toggle label="Share with someone"           value={!!t.hideShare}
              onChange={(v) => setTweak('hideShare', v)} />
      <Toggle label="Set up account"               value={!!t.hideSetupAccount}
              onChange={(v) => setTweak('hideSetupAccount', v)} />

      <Section label="" />
      <Button label="Restore default settings" secondary onClick={resetAll} />
    </Panel>
  );
}

function PoweredByZipper() {
  return (
    <div style={{
      padding: '36px 0 8px',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 10,
      fontSize: 10.5, fontWeight: 600, letterSpacing: '0.1em',
      textTransform: 'uppercase', color: '#9CA3AF',
    }}>
      <span>Powered by</span>
      <img src="zipper-logo-grey.svg" alt="Zipper" height="18"
           style={{ display: 'block', height: 18, width: 'auto' }} />
    </div>
  );
}

window.ConfirmationApp = ConfirmationApp;
const _cfRoot = document.getElementById('root');
if (_cfRoot && !_cfRoot.dataset.framed) {
  ReactDOM.createRoot(_cfRoot).render(<ConfirmationApp />);
}
