// components/widgets.jsx — Tonight's Sky, Moon Calendar, FAQ, Gallery, Tour Cards, Dark Sky Promise

// ── Tonight's Sky widget ─────────────────────────────────
function TonightsSky({ onBook }) {
  const moon = getMoonPhase();
  const best = moonBestFor(moon);
  const cloudRisk = 'Low';
  const dressNote = 'Bring a fleece — desert nights drop to 48°F.';

  const highlights = moon.illum < 30
    ? ['Milky Way core (rising 10pm)', 'Orion Nebula (M42)', 'Andromeda Galaxy (M31)', 'Pleiades cluster']
    : moon.illum > 80
    ? ['Tycho crater (full detail)', 'Mare Imbrium', 'Jupiter & 4 Galilean moons', 'Saturn (rings open 4°)']
    : ['Jupiter & moons', 'Saturn (rings)', 'Albireo double star', 'Ring Nebula (M57)'];

  return (
    <div className="card card--ink" style={{ padding: 0, overflow: 'hidden', position: 'relative' }}>
      <div style={{ padding: '32px 36px', display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'start' }}>
        <div>
          <div className="eyebrow on-night" style={{ marginBottom: 18 }}>Tonight in Sedona</div>
          <div className="display" style={{ fontSize: 'clamp(36px, 4vw, 54px)', marginBottom: 10 }}>
            <em>{best.tag}</em>
          </div>
          <div className="muted-night" style={{ fontFamily: 'var(--f-body)', fontSize: 17, fontStyle: 'italic', maxWidth: 480 }}>
            {best.desc}. Conditions are looking generous — exactly the kind of night you came to Sedona for.
          </div>
        </div>
        <MoonGlyph fraction={moon.fraction} size={84} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', borderTop: '1px solid var(--c-line-night)' }}>
        <Stat label="Moon" value={moon.name} />
        <Stat label="Illuminated" value={moon.illum + '%'} />
        <Stat label="Cloud risk" value={cloudRisk} />
        <Stat label="Dress" value="Layers + fleece" />
      </div>

      <div style={{ padding: '28px 36px', borderTop: '1px solid var(--c-line-night)' }}>
        <div className="eyebrow on-night" style={{ marginBottom: 14 }}>Tonight may include</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {highlights.map(h => (
            <span key={h} className="tag" style={{
              color: 'rgba(248,244,232,0.92)',
              borderColor: 'rgba(248,244,232,0.22)',
              fontFamily: 'var(--f-ui)',
              fontSize: 12.5,
              letterSpacing: '0.02em',
              textTransform: 'none',
              fontWeight: 500,
            }}>
              <IconStar size={11} stroke={1.6} /> {h}
            </span>
          ))}
        </div>
        <div style={{
          marginTop: 22,
          fontSize: 13.5,
          fontFamily: 'var(--f-body)',
          fontStyle: 'italic',
          color: 'rgba(248,244,232,0.6)',
          lineHeight: 1.55,
        }}>
          Not all objects are visible every night. Your guide chooses the best available
          targets based on the season, moon, and conditions. That's part of the magic.
        </div>
      </div>

      <div style={{
        padding: '22px 36px',
        borderTop: '1px solid var(--c-line-night)',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        gap: 16,
      }}>
        <span style={{ fontFamily: 'var(--f-ui)', fontSize: 13, color: 'rgba(248,244,232,0.7)' }}>
          Tonight's tour starts at 8:15 PM.
        </span>
        <button className="btn btn--moon btn--sm" onClick={onBook}>
          Reserve tonight <IconArrow size={14} />
        </button>
      </div>
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{
      padding: '20px 24px',
      borderRight: '1px solid var(--c-line-night)',
    }}>
      <div className="eyebrow on-night" style={{ fontSize: 10, marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: 'var(--f-display)', fontSize: 22, lineHeight: 1.1 }}>{value}</div>
    </div>
  );
}

// ── 7-night moon calendar ────────────────────────────────
function MoonCalendar({ onBook, days = 7, accent = 'paper' }) {
  const today = new Date();
  const items = [];
  for (let i = 0; i < days; i++) {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    const moon = getMoonPhase(d);
    items.push({ date: d, moon });
  }

  const onNight = accent === 'night';
  const lineColor = onNight ? 'var(--c-line-night)' : 'var(--c-line)';
  const inkColor = onNight ? 'var(--c-star)' : 'var(--c-ink)';

  return (
    <div style={{
      borderTop: `1px solid ${lineColor}`,
      borderBottom: `1px solid ${lineColor}`,
      color: inkColor,
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${days}, 1fr)` }}>
        {items.map((it, i) => {
          const best = moonBestFor(it.moon);
          const dow = it.date.toLocaleDateString('en', { weekday: 'short' });
          const day = it.date.getDate();
          const month = it.date.toLocaleDateString('en', { month: 'short' });
          const isDark = best.tag === 'Dark Sky Night';
          return (
            <div key={i} style={{
              padding: '28px 18px 24px',
              borderRight: i < days - 1 ? `1px solid ${lineColor}` : 'none',
              display: 'flex',
              flexDirection: 'column',
              gap: 14,
              position: 'relative',
            }}>
              {i === 0 && (
                <span style={{
                  position: 'absolute',
                  top: 10, right: 10,
                  fontFamily: 'var(--f-ui)', fontSize: 9.5, fontWeight: 600,
                  letterSpacing: '0.14em', textTransform: 'uppercase',
                  color: 'var(--c-rock)',
                }}>Tonight</span>
              )}
              <div>
                <div style={{ fontFamily: 'var(--f-ui)', fontSize: 11, letterSpacing: '0.12em',
                              textTransform: 'uppercase', opacity: 0.55, marginBottom: 6 }}>
                  {dow} · {month}
                </div>
                <div className="num" style={{ fontSize: 44 }}>{day}</div>
              </div>
              <MoonGlyph fraction={it.moon.fraction} size={42} />
              <div>
                <div style={{ fontFamily: 'var(--f-body)', fontSize: 14, fontStyle: 'italic',
                              color: onNight ? 'rgba(248,244,232,0.8)' : 'var(--c-mute)' }}>
                  {it.moon.name}
                </div>
                <div style={{ fontSize: 11.5, opacity: 0.55, fontFamily: 'var(--f-ui)', marginTop: 2 }}>
                  {it.moon.illum}% lit
                </div>
              </div>
              <span className={isDark ? 'tag tag--rock' : 'tag'} style={{
                fontSize: 10, padding: '4px 8px', letterSpacing: '0.08em',
                alignSelf: 'flex-start',
              }}>
                {isDark ? '★ Best' : best.tag.replace(' Night', '')}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── FAQ accordion ────────────────────────────────────────
function Accordion({ items, multi = false }) {
  const [open, setOpen] = React.useState({});
  const toggle = (i) => setOpen(o => multi
    ? { ...o, [i]: !o[i] }
    : (o[i] ? {} : { [i]: true }));

  return (
    <div>
      {items.map((it, i) => (
        <div key={i} className="faq-item">
          <button className="faq-q" onClick={() => toggle(i)}>
            <span>{it.q}</span>
            <span style={{
              width: 36, height: 36, borderRadius: '50%',
              border: '1px solid var(--c-line)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
              transform: open[i] ? 'rotate(45deg)' : 'rotate(0)',
              transition: 'transform 0.25s ease',
            }}>
              <IconPlus size={14} stroke={1.6} />
            </span>
          </button>
          {open[i] && (
            <div className="faq-a" style={{ whiteSpace: 'pre-line' }}>
              {it.a}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ── Tour Cards ───────────────────────────────────────────
const TOURS = [
  {
    id: 'public',
    name: 'Sedona Star Show',
    sub: 'The flagship public tour',
    price: 117,
    childPrice: 76,
    duration: '2 hrs',
    size: 'Up to 10 guests',
    age: 'Ages 5+',
    location: 'Permitted dark-sky site, 18 min from Uptown',
    badge: 'Most booked',
    gradient: 'linear-gradient(135deg, #07111F, #182A46)',
    bullets: [
      'Constellation tour with green laser pointer',
      'Six or more telescope objects',
      'Celestron 8″ SCT &amp; 11″ Dobsonian',
      'Camp chairs, blankets, parka jackets provided',
      'Round-trip Uptown shuttle add-on available',
    ],
  },
  {
    id: 'private',
    name: 'Private Star Show',
    sub: 'For your group only',
    price: 1200,
    priceUnit: 'flat · up to 8',
    duration: '2.5 hrs',
    size: 'Private group',
    age: 'All ages',
    location: 'Your vacation rental, resort, or our site',
    badge: 'Vacation rentals',
    gradient: 'linear-gradient(135deg, #2a1d1a, #5a2a1c)',
    bullets: [
      'Personalized to your group&apos;s interests',
      'Perfect for proposals, birthdays, family nights',
      'Optional astrophotography session',
      'We come to your rental within 30 min of Sedona',
      'Sparkling cider toast included',
    ],
  },
  {
    id: 'moon',
    name: 'Moon &amp; Planets Night',
    sub: 'For bright-moon nights',
    price: 95,
    childPrice: 62,
    duration: '90 min',
    size: 'Up to 10 guests',
    age: 'Ages 5+',
    location: 'Uptown overlook',
    badge: 'Moon-friendly',
    gradient: 'linear-gradient(135deg, #1c1a14, #4a3a1a)',
    bullets: [
      'Lunar crater tour (Tycho, Copernicus, Plato)',
      'Jupiter &amp; the Galilean moons',
      'Saturn when up — rings visible',
      'Great when full moon blocks deep sky',
      'Shorter format, kid-friendly pacing',
    ],
  },
  {
    id: 'event',
    name: 'Special Sky Events',
    sub: 'Meteor showers &amp; eclipses',
    price: 145,
    childPrice: 92,
    duration: '3 hrs',
    size: 'Up to 14 guests',
    age: 'Ages 8+',
    location: 'Best-conditions site, announced 48hr prior',
    badge: 'Limited dates',
    gradient: 'linear-gradient(135deg, #1f0a1a, #4a1538)',
    bullets: [
      'Perseids, Geminids, Quadrantids, eclipses',
      'Extended viewing window',
      'Storytelling around the meteor radiant',
      'Hot cocoa, blankets, reclining mats',
      'Astrophoto coaching for your phone',
    ],
  },
];

function TourCard({ tour, onBook, onSelect }) {
  return (
    <div style={{
      borderRadius: 'var(--r-lg)',
      overflow: 'hidden',
      background: 'var(--c-paper)',
      border: '1px solid var(--c-line)',
      display: 'flex',
      flexDirection: 'column',
      transition: 'transform 0.2s ease, border-color 0.2s ease',
    }}>
      <div style={{
        height: 180,
        background: tour.gradient,
        position: 'relative',
        padding: 20,
      }}>
        <StarField stars={makeStars(35, tour.id.charCodeAt(0))} opacity={0.9} />
        <span className="tag" style={{
          position: 'absolute', top: 16, left: 16,
          color: 'rgba(248,244,232,0.92)',
          borderColor: 'rgba(248,244,232,0.32)',
          background: 'rgba(0,0,0,0.25)',
          backdropFilter: 'blur(4px)',
        }}>{tour.badge}</span>
        <div style={{
          position: 'absolute', bottom: 18, left: 20, right: 20,
          color: 'var(--c-star)',
        }}>
          <div className="display" style={{ fontSize: 28, lineHeight: 1.05 }}
               dangerouslySetInnerHTML={{ __html: tour.name }} />
          <div style={{ fontFamily: 'var(--f-body)', fontSize: 14, fontStyle: 'italic',
                        color: 'rgba(248,244,232,0.7)', marginTop: 4 }}>{tour.sub}</div>
        </div>
      </div>

      <div style={{ padding: '22px 24px', display: 'flex', flexDirection: 'column', gap: 16, flex: 1 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, paddingBottom: 16,
                      borderBottom: '1px solid var(--c-line-soft)' }}>
          <Spec icon={<IconClock size={14} />} label="Duration" value={tour.duration} />
          <Spec icon={<IconUsers size={14} />} label="Group" value={tour.size} />
          <Spec icon={<IconSparkle size={14} />} label="Ages" value={tour.age} />
          <Spec icon={<IconMap size={14} />} label="Location" value={tour.location} />
        </div>

        <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {tour.bullets.map((b, i) => (
            <li key={i} style={{ display: 'flex', gap: 10, fontFamily: 'var(--f-body)', fontSize: 14.5, lineHeight: 1.45 }}>
              <IconCheck size={14} stroke={2} style={{ color: 'var(--c-rock)', flexShrink: 0, marginTop: 4 }} />
              <span dangerouslySetInnerHTML={{ __html: b }} />
            </li>
          ))}
        </ul>

        <div style={{ marginTop: 'auto', paddingTop: 16, borderTop: '1px solid var(--c-line-soft)',
                      display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <div className="num" style={{ fontSize: 32, lineHeight: 1 }}>
              ${tour.price}
              <span style={{ fontSize: 13, fontFamily: 'var(--f-ui)', color: 'var(--c-mute)', marginLeft: 6, letterSpacing: 0 }}>
                {tour.priceUnit || (tour.childPrice ? `adult · $${tour.childPrice} child` : '')}
              </span>
            </div>
          </div>
          <button className="btn btn--primary btn--sm" onClick={() => onBook(tour)}>
            Book <IconArrow size={14} />
          </button>
        </div>
      </div>
    </div>
  );
}

function Spec({ icon, label, value }) {
  return (
    <div style={{ display: 'flex', gap: 10 }}>
      <span style={{ color: 'var(--c-mute)', marginTop: 2 }}>{icon}</span>
      <div>
        <div style={{ fontFamily: 'var(--f-ui)', fontSize: 10, letterSpacing: '0.12em',
                      textTransform: 'uppercase', color: 'var(--c-mute)' }}>{label}</div>
        <div style={{ fontFamily: 'var(--f-ui)', fontSize: 13, fontWeight: 500, marginTop: 2 }}>{value}</div>
      </div>
    </div>
  );
}

// ── Dark Sky Promise ─────────────────────────────────────
function DarkSkyPromise() {
  const promises = [
    { icon: <IconShield size={20} />, t: 'Low, warm, controlled light', d: 'No bright white flashlights. Red headlamps only.' },
    { icon: <IconUsers size={20} />, t: 'Small groups, always', d: 'Maximum 10 guests per public tour.' },
    { icon: <IconLeaf size={20} />, t: 'Leave No Trace', d: 'Pack in, pack out. We bring trash bags.' },
    { icon: <IconMap size={20} />, t: 'Quiet sites, respected', d: 'We rotate locations to protect fragile dark-sky spots.' },
    { icon: <IconChat size={20} />, t: 'Quiet hours, respected', d: 'Voices low after 10 PM near residential areas.' },
    { icon: <IconStar size={20} />, t: 'Teach the next dark', d: 'Every guest leaves with one thing they can do at home.' },
  ];
  return (
    <div style={{ background: 'var(--c-ink)', color: 'var(--c-star)', borderRadius: 'var(--r-xl)',
                  padding: 'clamp(40px, 6vw, 72px)', position: 'relative', overflow: 'hidden' }}>
      <StarField stars={makeStars(45, 99)} opacity={0.55} />
      <div style={{ position: 'relative' }}>
        <div className="eyebrow on-night" style={{ marginBottom: 22 }}>★ Our Dark Sky Promise</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1.4fr', gap: 64, alignItems: 'start' }}
             className="dsp-grid">
          <div>
            <h2 className="display" style={{ fontSize: 'clamp(40px, 5vw, 64px)', margin: '0 0 24px' }}>
              We promise to leave the <em>dark</em> the way we found it.
            </h2>
            <p className="lead" style={{ color: 'rgba(248,244,232,0.78)', maxWidth: 460 }}>
              Sedona became an International Dark Sky Community in 2014.
              That status is fragile, and we take real responsibility for protecting it.
            </p>
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }}>
            {promises.map((p, i) => (
              <li key={i} style={{ display: 'flex', gap: 14 }}>
                <span style={{ color: 'var(--c-moon)', flexShrink: 0 }}>{p.icon}</span>
                <div>
                  <div style={{ fontFamily: 'var(--f-display)', fontSize: 19, lineHeight: 1.2, marginBottom: 4 }}>{p.t}</div>
                  <div style={{ fontFamily: 'var(--f-body)', fontSize: 14, color: 'rgba(248,244,232,0.65)', lineHeight: 1.5 }}>{p.d}</div>
                </div>
              </li>
            ))}
          </ul>
        </div>
        <style>{`
          @media (max-width: 880px) {
            .dsp-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
            .dsp-grid ul { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>
    </div>
  );
}

// ── Photo placeholder + Gallery lightbox ─────────────────
const GALLERY = [
  { id: 'g1', title: 'Cathedral Rock at twilight', kind: 'landscape',
    grad: 'linear-gradient(160deg, #182A46 0%, #3a2046 30%, #9b3a4b 65%, #d97243 100%)' },
  { id: 'g2', title: 'Saturn through the 8″', kind: 'planet',
    grad: 'radial-gradient(circle at 50% 50%, #1a2745, #07111f)' },
  { id: 'g3', title: 'Orion Nebula (M42)', kind: 'deepsky',
    grad: 'radial-gradient(circle at 40% 50%, #d97243 0%, #9b3a4b 20%, #182A46 60%, #07111f 100%)' },
  { id: 'g4', title: 'Milky Way over the red rocks', kind: 'milkyway',
    grad: 'linear-gradient(180deg, #07111F 0%, #182A46 50%, #2a1428 80%, #1a0a08 100%)' },
  { id: 'g5', title: 'Guest at the eyepiece', kind: 'guest',
    grad: 'linear-gradient(135deg, #3a2046, #1c2a4c)' },
  { id: 'g6', title: 'Andromeda Galaxy (M31)', kind: 'deepsky',
    grad: 'radial-gradient(ellipse at 50% 50%, #e8cfa8 0%, #b65a3c 8%, #182A46 45%, #07111f 100%)' },
  { id: 'g7', title: 'Telescope setup at dusk', kind: 'setup',
    grad: 'linear-gradient(180deg, #b65a3c, #5a2a1c 65%, #1a0a08)' },
  { id: 'g8', title: 'Perseid meteor shower', kind: 'meteor',
    grad: 'linear-gradient(135deg, #07111f, #182A46)' },
];

function PhotoPlaceholder({ item, onClick, style }) {
  return (
    <div onClick={onClick} className="ph" style={{
      ...style,
      background: item.grad,
      cursor: onClick ? 'pointer' : 'default',
      position: 'relative',
    }}>
      {/* Decorative elements depending on kind */}
      {item.kind === 'milkyway' && <StarField stars={makeStars(80, item.id.charCodeAt(1))} opacity={0.95} />}
      {item.kind === 'meteor' && (
        <>
          <StarField stars={makeStars(120, 5)} opacity={0.95} />
          <svg style={{ position: 'absolute', inset: 0 }} viewBox="0 0 400 300" preserveAspectRatio="none">
            {[[40,30,180,90],[200,20,330,110],[100,140,260,210]].map(([x1,y1,x2,y2],i) => (
              <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="white" strokeWidth="1.5" opacity="0.6" />
            ))}
          </svg>
        </>
      )}
      {item.kind === 'planet' && (
        <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} viewBox="0 0 400 300">
          <ellipse cx="200" cy="155" rx="100" ry="14" fill="none" stroke="#d6b878" strokeWidth="2" opacity="0.8" />
          <circle cx="200" cy="150" r="40" fill="#e6c98a" />
          <path d="M 100,155 A 100,14 0 0 0 300,155" fill="none" stroke="#e6c98a" strokeWidth="2" />
        </svg>
      )}
      <div className="ph-label">{item.title}</div>
    </div>
  );
}

function Gallery({ items = GALLERY }) {
  const [open, setOpen] = React.useState(null);
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}
           className="gal-grid">
        {items.map((it, i) => (
          <PhotoPlaceholder
            key={it.id}
            item={it}
            onClick={() => setOpen(i)}
            style={{
              aspectRatio: i % 5 === 0 ? '2 / 1' : '1 / 1',
              gridColumn: i % 5 === 0 ? 'span 2' : 'span 1',
              height: i % 5 === 0 ? undefined : undefined,
            }}
          />
        ))}
      </div>
      <style>{`
        @media (max-width: 880px) {
          .gal-grid { grid-template-columns: 1fr 1fr !important; }
          .gal-grid > div { grid-column: span 1 !important; aspect-ratio: 1 / 1 !important; }
        }
      `}</style>

      {open !== null && (
        <div className="modal-bg" onClick={() => setOpen(null)}>
          <div style={{
            position: 'relative', maxWidth: 1000, width: '100%', maxHeight: '90vh',
            display: 'flex', flexDirection: 'column', gap: 12,
          }} onClick={e => e.stopPropagation()}>
            <button onClick={() => setOpen(null)} aria-label="Close" style={{
              position: 'absolute', top: -42, right: 0, background: 'transparent',
              border: 0, color: 'white',
            }}><IconClose size={22} /></button>
            <PhotoPlaceholder item={items[open]} style={{ aspectRatio: '16 / 10', borderRadius: 16 }} />
            <div style={{ color: 'white', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                          fontFamily: 'var(--f-ui)', fontSize: 13 }}>
              <span>{items[open].title}</span>
              <span style={{ display: 'flex', gap: 8 }}>
                <button className="btn btn--sm btn--ghost-night" onClick={() => setOpen((open - 1 + items.length) % items.length)}>← Prev</button>
                <button className="btn btn--sm btn--ghost-night" onClick={() => setOpen((open + 1) % items.length)}>Next →</button>
              </span>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

// ── Section header ──────────────────────────────────────
function SectionHead({ kicker, title, intro, align = 'left', onNight = false }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === 'center' ? 720 : 880, margin: align === 'center' ? '0 auto' : undefined }}>
      <div className={onNight ? 'eyebrow on-night' : 'eyebrow'} style={{ marginBottom: 18 }}>{kicker}</div>
      <h2 className="display" style={{
        fontSize: 'clamp(38px, 5vw, 72px)', margin: '0 0 22px',
        color: onNight ? 'var(--c-star)' : 'var(--c-ink)',
      }} dangerouslySetInnerHTML={{ __html: title }} />
      {intro && (
        <p className="lead" style={{
          color: onNight ? 'rgba(248,244,232,0.78)' : 'var(--c-mute)',
          maxWidth: 580,
          margin: align === 'center' ? '0 auto' : undefined,
        }}>{intro}</p>
      )}
    </div>
  );
}

Object.assign(window, {
  TonightsSky, MoonCalendar, Accordion, TourCard, TOURS, Spec,
  DarkSkyPromise, PhotoPlaceholder, Gallery, GALLERY, SectionHead, Stat,
});
