const { useState, useEffect, useRef } = React;

// ==================== ORNAMENT ====================
function Ornament({ name, size = 80, color = 'var(--gold-600)', className = '', style = {} }) {
  return (
    <div
      className={`ornament ${className}`}
      style={{
        width: size, height: size, color,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        ...style,
      }}
    >
      <img
        src={`../../assets/ornaments/${name}.svg`}
        style={{ width: '100%', height: '100%', filter: 'drop-shadow(0 1px 0 rgba(122,31,43,.05))' }}
        alt=""
      />
    </div>
  );
}

// ==================== DIVIDER ====================
function Divider({ label, width = 360 }) {
  return (
    <div className="divider-wrap" style={{ display:'flex', alignItems:'center', gap:12, width, margin:'var(--sp-5) auto' }}>
      <div style={{ flex:1, height:1, background:'linear-gradient(90deg, transparent, var(--gold-500))' }} />
      {label && (
        <div style={{ fontFamily:'var(--font-ui)', fontSize:11, letterSpacing:'.28em', textTransform:'uppercase', color:'var(--gold-700)' }}>
          {label}
        </div>
      )}
      <div style={{ flex:1, height:1, background:'linear-gradient(-90deg, transparent, var(--gold-500))' }} />
    </div>
  );
}

// ==================== BUTTON ====================
function Button({ variant = 'primary', size = 'md', children, onClick, ...rest }) {
  const base = {
    fontFamily:'var(--font-ui)',
    fontSize: size === 'sm' ? 12 : 14,
    letterSpacing:'.18em',
    textTransform:'uppercase',
    padding: size === 'sm' ? '8px 18px' : '14px 28px',
    borderRadius: 999,
    border: '1.5px solid var(--gold-500)',
    cursor: 'pointer',
    transition: 'all .18s cubic-bezier(.2,.8,.2,1)',
  };
  const variants = {
    primary: { background: 'var(--marsala-700)', color: 'var(--ivory-100)' },
    secondary: { background: 'transparent', color: 'var(--marsala-700)' },
    gold: { background: 'linear-gradient(180deg, #D9B15F, #C79A3A)', color: 'var(--marsala-900)', borderColor: 'var(--gold-700)' },
    ghost: { background: 'transparent', color: 'var(--gold-700)', border: '1px solid transparent' },
  };
  return (
    <button
      onClick={onClick}
      className="btn"
      style={{ ...base, ...variants[variant] }}
      onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
      {...rest}
    >
      {children}
    </button>
  );
}

// ==================== CORNER FRAME ====================
function CornerFrame({ children, style = {}, className = '' }) {
  const corner = (transform) => (
    <img
      src="../../assets/ornaments/corner.svg"
      style={{
        position:'absolute', width: 48, height: 48, color: 'var(--gold-600)',
        opacity: .75, ...transform,
      }}
      alt=""
    />
  );
  return (
    <div className={className} style={{ position:'relative', ...style }}>
      <div style={{ position:'absolute', top:8, left:8, width:48, height:48 }}><img src="../../assets/ornaments/corner.svg" style={{ width:'100%', height:'100%', opacity:.75 }} /></div>
      <div style={{ position:'absolute', top:8, right:8, width:48, height:48, transform:'scaleX(-1)' }}><img src="../../assets/ornaments/corner.svg" style={{ width:'100%', height:'100%', opacity:.75 }} /></div>
      <div style={{ position:'absolute', bottom:8, left:8, width:48, height:48, transform:'scaleY(-1)' }}><img src="../../assets/ornaments/corner.svg" style={{ width:'100%', height:'100%', opacity:.75 }} /></div>
      <div style={{ position:'absolute', bottom:8, right:8, width:48, height:48, transform:'scale(-1,-1)' }}><img src="../../assets/ornaments/corner.svg" style={{ width:'100%', height:'100%', opacity:.75 }} /></div>
      {children}
    </div>
  );
}

// ==================== SAVE-THE-DATE (calendar links) ====================
// Event metadata — single source of truth.
const WEDDING_EVENT = {
  title:      'Keerthi & Gopichand — Wedding',
  details:    'The wedding of Keerthi & Gopichand. Sumuhurtham at 9:35 A.M. Lunch follows the ceremony.',
  location:   'Anvitha Gardens, Near Matha Manikeshwari Temple, Theegalaguttapalli, Karimnagar, Telangana',
  // Local IST → UTC for cross-calendar URLs (9:35 IST = 04:05 UTC)
  startUTC:   '20260509T040500Z',
  endUTC:     '20260509T073000Z',
  startLocal: '20260509T093500', // for ICS with TZID
  endLocal:   '20260509T130000',
  tz:         'Asia/Kolkata',
};

function buildICS() {
  const e = WEDDING_EVENT;
  const dtstamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
  const esc = (s) => String(s).replace(/[\\,;]/g, (m) => '\\' + m).replace(/\n/g, '\\n');
  return [
    'BEGIN:VCALENDAR', 'VERSION:2.0',
    'PRODID:-//Keerthi-Gopichand//Wedding//EN',
    'CALSCALE:GREGORIAN', 'METHOD:PUBLISH',
    'BEGIN:VEVENT',
    `UID:${Date.now()}-keerthi-gopichand-wedding@invitation`,
    `DTSTAMP:${dtstamp}`,
    `DTSTART;TZID=${e.tz}:${e.startLocal}`,
    `DTEND;TZID=${e.tz}:${e.endLocal}`,
    `SUMMARY:${esc(e.title)}`,
    `DESCRIPTION:${esc(e.details)}`,
    `LOCATION:${esc(e.location)}`,
    'BEGIN:VALARM', 'ACTION:DISPLAY',
    'DESCRIPTION:Wedding tomorrow — Keerthi & Gopichand',
    'TRIGGER:-P1D',
    'END:VALARM',
    'END:VEVENT', 'END:VCALENDAR',
  ].join('\r\n');
}

function calendarLinks() {
  const e = WEDDING_EVENT;
  const enc = encodeURIComponent;
  return {
    google: `https://calendar.google.com/calendar/render?action=TEMPLATE`
      + `&text=${enc(e.title)}`
      + `&dates=${e.startUTC}/${e.endUTC}`
      + `&details=${enc(e.details)}`
      + `&location=${enc(e.location)}`
      + `&ctz=${enc(e.tz)}`,
    outlook: `https://outlook.live.com/calendar/0/deeplink/compose?path=/calendar/action/compose&rru=addevent`
      + `&subject=${enc(e.title)}`
      + `&body=${enc(e.details)}`
      + `&location=${enc(e.location)}`
      + `&startdt=${enc('2026-05-09T09:35:00+05:30')}`
      + `&enddt=${enc('2026-05-09T13:00:00+05:30')}`,
    yahoo: `https://calendar.yahoo.com/?v=60&view=d&type=20`
      + `&title=${enc(e.title)}`
      + `&st=${e.startUTC}&et=${e.endUTC}`
      + `&desc=${enc(e.details)}`
      + `&in_loc=${enc(e.location)}`,
    ics: 'data:text/calendar;charset=utf-8,' + encodeURIComponent(buildICS()),
  };
}

function isIOS() {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}

function downloadWeddingICS() {
  // Apple Calendar (Mac) or generic .ics download. iOS Safari handles
  // text/calendar from blob URLs by offering "Open in Calendar".
  const ics = buildICS();
  const blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  if (!isIOS()) a.download = 'keerthi-gopichand-wedding.ics';
  // iOS: omit `download` so Safari opens it in Calendar instead of saving
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1500);
}

// Pill button — double-rule gold border, soft marsala tint, calendar icon
// so it reads as a clear action. Used on the cover under "Open the Invitation".
// On click, opens a small picker so guests pick their preferred calendar.
function SaveTheDateButton({ phase = 4, onClick, dark = true }) {
  const ready = phase >= 4;
  const [hover, setHover] = React.useState(false);
  const [press, setPress] = React.useState(false);
  const [open, setOpen]   = React.useState(false);
  const wrapRef = React.useRef(null);

  const links = React.useMemo(() => calendarLinks(), []);

  // Close popover on outside click / Esc
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('pointerdown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('pointerdown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const pickGoogle  = () => { window.open(links.google,  '_blank', 'noopener'); setOpen(false); };
  const pickOutlook = () => { window.open(links.outlook, '_blank', 'noopener'); setOpen(false); };
  const pickYahoo   = () => { window.open(links.yahoo,   '_blank', 'noopener'); setOpen(false); };
  const pickApple   = () => { downloadWeddingICS(); setOpen(false); };

  const handle = (e) => {
    e.preventDefault();
    if (onClick) { onClick(); return; }
    // iOS: link to the static .ics. Safari sees `text/calendar` MIME and
    //   offers "Add to Calendar" in Apple Calendar.
    // Android / Desktop: open Google Calendar with the event pre-filled
    //   (Android intercepts and opens the Google Calendar app).
    if (isIOS()) {
      window.location.href = 'assets/wedding.ics';
    } else {
      window.open(links.google, '_blank', 'noopener');
    }
  };

  const { motion, AnimatePresence } = window.Motion || {};

  // Measure the button so the portalled popover sits just above it.
  const btnRef = React.useRef(null);
  const [pos, setPos] = React.useState({ left: 0, bottom: 0 });
  const measure = React.useCallback(() => {
    const el = btnRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    setPos({
      left: r.left + r.width / 2,
      bottom: window.innerHeight - r.top + 12, // 12px gap above the button
    });
  }, []);
  React.useEffect(() => {
    if (!open) return;
    measure();
    window.addEventListener('resize', measure);
    window.addEventListener('scroll', measure, true);
    return () => {
      window.removeEventListener('resize', measure);
      window.removeEventListener('scroll', measure, true);
    };
  }, [open, measure]);
  const tint = dark
    ? (hover ? 'rgba(74,17,25,.65)' : 'rgba(74,17,25,.45)')
    : (hover ? 'rgba(251,243,227,.95)' : 'rgba(254,251,244,.85)');
  const menuItem = (label, sub, onPick) => (
    <button type="button" onClick={onPick} key={label}
      style={{
        display:'flex', alignItems:'center', gap:10,
        width:'100%', padding:'10px 14px',
        background:'transparent', border:'none',
        color: dark ? 'var(--ivory-50)' : 'var(--ink-800)',
        fontFamily:'var(--font-ui)', fontSize:12, letterSpacing:'.06em',
        textAlign:'left', cursor:'pointer', borderRadius:8,
        transition:'background .15s ease',
        touchAction:'manipulation',
      }}
      onMouseEnter={(e) => e.currentTarget.style.background = dark ? 'rgba(229,193,104,.12)' : 'rgba(122,31,43,.06)'}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <span style={{ fontFamily:'var(--font-display)', fontStyle:'italic', color:'var(--gold-500)', minWidth:24 }}>★</span>
      <span style={{ flex:1 }}>
        <div style={{ fontWeight:500 }}>{label}</div>
        {sub && <div style={{ fontSize:10, opacity:.7, marginTop:2 }}>{sub}</div>}
      </span>
    </button>
  );

  return (
    <div ref={wrapRef} style={{ position:'relative', display:'inline-block', marginTop: 14, zIndex: 30 }}>
      <button
        ref={btnRef}
        type="button"
        onClick={handle}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => { setHover(false); setPress(false); }}
        onMouseDown={() => setPress(true)}
        onMouseUp={() => setPress(false)}
        aria-label="Save the date — add to calendar"
        aria-expanded={open}
        style={{
          position: 'relative',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          background: tint,
          backdropFilter: dark ? 'blur(6px)' : 'none',
          color: dark ? '#FFE9B0' : 'var(--marsala-700)',
          fontFamily: 'var(--font-ui)', fontSize: 12, letterSpacing: '.32em', fontWeight: 500,
          textTransform: 'uppercase',
          padding: '13px 26px',
          border: '1.5px solid ' + (dark ? 'var(--gold-400)' : 'var(--gold-600)'),
          borderRadius: 999,
          outline: '1px solid ' + (dark ? 'rgba(229,193,104,.65)' : 'rgba(199,154,58,.7)'),
          outlineOffset: '4px',
          cursor: 'pointer',
          opacity: ready ? 1 : 0,
          transform: ready
            ? (press ? 'scale(.97)' : (hover ? 'translateY(-2px)' : 'translateY(0)'))
            : 'translateY(8px)',
          transition: 'opacity .9s ease .9s, transform .25s cubic-bezier(.2,.8,.2,1), background .25s ease, box-shadow .25s ease',
          pointerEvents: ready ? 'auto' : 'none',
          boxShadow: hover
            ? (dark
                ? '0 10px 28px rgba(0,0,0,.45), 0 0 0 1px rgba(229,193,104,.55), 0 0 22px rgba(229,193,104,.25)'
                : '0 10px 22px rgba(122,31,43,.18), 0 0 0 1px rgba(199,154,58,.35)')
            : (dark
                ? '0 6px 18px rgba(0,0,0,.35)'
                : '0 6px 14px rgba(122,31,43,.10)'),
          touchAction: 'manipulation',
          WebkitTapHighlightColor: 'rgba(229,193,104,.3)',
          WebkitAppearance: 'none',
        }}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
             stroke="currentColor" strokeWidth="1.8"
             strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <rect x="3" y="5" width="18" height="16" rx="2" />
          <line x1="3" y1="10" x2="21" y2="10" />
          <line x1="8" y1="3" x2="8" y2="7" />
          <line x1="16" y1="3" x2="16" y2="7" />
          <line x1="12" y1="13" x2="12" y2="17" />
          <line x1="10" y1="15" x2="14" y2="15" />
        </svg>
        <span>Save the Date</span>
      </button>

      {/* Calendar picker — portalled to body so it escapes section overflow:hidden */}
      {motion && AnimatePresence && ReactDOM.createPortal(
        <AnimatePresence>
          {open && (
            <motion.div
              key="cal-menu"
              initial={{ opacity: 0, y: 8, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 8, scale: 0.95 }}
              transition={{ type:'spring', stiffness: 240, damping: 22 }}
              role="menu"
              style={{
                position:'fixed',
                left: pos.left,
                bottom: pos.bottom,
                transform: 'translateX(-50%)',
                minWidth: 240,
                padding: 10,
                background: dark ? 'rgba(26,8,11,.96)' : 'var(--ivory-50)',
                border: '1px solid var(--gold-500)',
                borderRadius: 14,
                boxShadow: dark
                  ? '0 18px 44px rgba(0,0,0,.55), 0 0 0 1px rgba(229,193,104,.25)'
                  : '0 18px 44px rgba(122,31,43,.18), 0 0 0 1px rgba(199,154,58,.25)',
                zIndex: 9000,
                backdropFilter: 'blur(8px)',
              }}
            >
              <div style={{
                fontFamily:'var(--font-ui)', fontSize:9, letterSpacing:'.34em',
                textTransform:'uppercase',
                color: 'var(--gold-500)',
                padding:'4px 10px 8px', textAlign:'left',
              }}>
                Add to Calendar
              </div>
              {menuItem('Apple Calendar',  isIOS() ? 'Opens Calendar app' : 'Downloads .ics file', pickApple)}
              {menuItem('Google Calendar', 'Opens in browser / app',                                pickGoogle)}
              {menuItem('Outlook',         'Opens outlook.live.com',                               pickOutlook)}
              {menuItem('Yahoo',           'Opens calendar.yahoo.com',                             pickYahoo)}
              <div style={{
                position:'absolute', bottom:-7, left:'50%', transform:'translateX(-50%) rotate(45deg)',
                width:12, height:12,
                background: dark ? 'rgba(26,8,11,.96)' : 'var(--ivory-50)',
                borderRight:'1px solid var(--gold-500)',
                borderBottom:'1px solid var(--gold-500)',
              }}/>
            </motion.div>
          )}
        </AnimatePresence>,
        document.body
      )}
    </div>
  );
}

Object.assign(window, { Ornament, Divider, Button, CornerFrame, SaveTheDateButton, downloadWeddingICS, calendarLinks, buildICS });
