/* App root */
const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#C75A3A",
  "background": "#F6F2E8",
  "displayFont": "DM Serif Display",
  "bodyFont": "Geist",
  "heroVariant": "imac",
  "heroBackground": "paper",
  "showLiveTag": true,
  "showFloatingStat": true
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  { label: 'Terracotta', value: '#C75A3A' },
  { label: 'Forest', value: '#3F6B45' },
  { label: 'Ink', value: '#15140F' },
  { label: 'Royal', value: '#3346B5' },
  { label: 'Mustard', value: '#C58E2A' },
];

const BG_OPTIONS = [
  { label: 'Cream', value: '#F6F2E8' },
  { label: 'Off-white', value: '#FAFAF7' },
  { label: 'Mist', value: '#EEF1ED' },
  { label: 'Sand', value: '#EFE7D7' },
];

const DISPLAY_FONTS = [
  { label: 'Instrument Serif', value: 'Instrument Serif' },
  { label: 'Fraunces', value: 'Fraunces' },
  { label: 'GT Sectra-ish', value: 'DM Serif Display' },
  { label: 'Big Shoulders', value: 'Big Shoulders Display' },
];
const BODY_FONTS = [
  { label: 'Geist', value: 'Geist' },
  { label: 'Inter', value: 'Inter' },
  { label: 'DM Sans', value: 'DM Sans' },
];

function Nav() {
  const [scrolled, setScrolled] = useStateA(false);
  useEffectA(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-row">
        <a href="/" className="brand" aria-label="Roomsy">
          <img src="images/toggle-logo.png" alt="Roomsy" height="28" style={{ height: 28, width: 'auto', display: 'block' }} />
        </a>
        <div className="nav-links">
          <a href="#built-for" className="nav-link">Product</a>
          <a href="#integrations" className="nav-link">Channels</a>
          <a href="#features" className="nav-link">Features</a>
          <a href="/pricing/" className="nav-link">Pricing</a>
          <a href="#testimonials" className="nav-link">Customers</a>
        </div>
        <div className="nav-cta">
          <a href="https://secure.roomsy.com" className="btn btn-ghost" style={{ padding: '10px 14px', fontSize: 13 }}>Log in</a>
          <a href="https://secure.roomsy.com/signup" className="btn btn-primary" style={{ padding: '10px 16px', fontSize: 13 }}>Start free trial <Icon name="arrow" size={14} /></a>
        </div>
      </div>
    </nav>
  );
}

function HeroAurora() {
  // Generate a proper dotted-globe wireframe: latitude/longitude grid projected
  // orthographically. Dots only on the visible hemisphere — gives real sphere
  // depth instead of flat concentric circles.
  const sphereDots = [];
  const LAT = 18, LON = 36, R = 360;
  for (let i = 1; i < LAT; i++) {
    const phi = (i / LAT) * Math.PI - Math.PI / 2; // -90 → 90
    for (let j = 0; j < LON; j++) {
      const theta = (j / LON) * Math.PI * 2;       // 0 → 360
      const x = Math.cos(phi) * Math.cos(theta);
      const y = Math.sin(phi);
      const z = Math.cos(phi) * Math.sin(theta);
      // orthographic projection — only show front hemisphere (z > 0)
      const sx = 400 + x * R;
      const sy = 400 + y * R;
      const opacity = z > 0 ? Math.min(0.55, 0.18 + z * 0.55) : 0;
      const r = z > 0 ? 0.6 + z * 1.4 : 0;
      if (opacity > 0) sphereDots.push({ sx, sy, r, opacity });
    }
  }
  return (
    <div className="hero-bg" aria-hidden="true">
      {/* layered mesh-gradient — three drifting color blobs */}
      <div className="hero-bg-mesh">
        <span className="blob b1" />
        <span className="blob b2" />
        <span className="blob b3" />
        <span className="blob b4" />
      </div>

      {/* dotted globe wireframe */}
      <div className="hero-bg-globe-wrap">
        <svg className="hero-bg-globe" viewBox="0 0 800 800" preserveAspectRatio="xMidYMid meet">
          <g>
            {sphereDots.map((d, i) => (
              <circle key={i} cx={d.sx} cy={d.sy} r={d.r} fill="white" opacity={d.opacity} />
            ))}
          </g>
        </svg>
      </div>

      {/* sweeping orbital arcs */}
      <svg className="hero-bg-orbits" viewBox="0 0 1200 700" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id="orbitFade" x1="0%" x2="100%">
            <stop offset="0%" stopColor="white" stopOpacity="0" />
            <stop offset="50%" stopColor="white" stopOpacity="0.5" />
            <stop offset="100%" stopColor="white" stopOpacity="0" />
          </linearGradient>
        </defs>
        <ellipse cx="900" cy="380" rx="640" ry="200" fill="none" stroke="url(#orbitFade)" strokeWidth="1" transform="rotate(-12 900 380)" />
        <ellipse cx="900" cy="380" rx="780" ry="240" fill="none" stroke="url(#orbitFade)" strokeWidth="1" strokeDasharray="2 8" transform="rotate(-12 900 380)" opacity="0.6" />
        <ellipse cx="900" cy="380" rx="500" ry="160" fill="none" stroke="url(#orbitFade)" strokeWidth="1" transform="rotate(8 900 380)" opacity="0.5" />
      </svg>

      {/* film grain + vignette */}
      <div className="hero-bg-grain" />
      <div className="hero-bg-vignette" />
    </div>
  );
}

function Hero({ tweaks, onWatchDemo }) {
  return (
    <section className={`hero ${tweaks.heroBackground === 'aurora' ? 'hero-aurora' : ''}`}>
      {tweaks.heroBackground === 'aurora' && <HeroAurora />}
      <div className="container hero-grid">
        <div>
          <h1 className="h-display">
            Hotel PMS your front desk <em>actually likes.</em>
          </h1>
          <p className="hero-sub">
            Cloud-based hotel management software for independent hotels, B&amp;Bs, hostels and motels. One calendar for every booking, every channel, every property — built for the kind of independent hosts who still answer the phone themselves.
          </p>
          <div className="hero-actions">
            <a href="https://secure.roomsy.com/signup" className="btn btn-primary" style={{ padding: '14px 20px', fontSize: 14 }}>
              Start a free trial <Icon name="arrow" size={14} />
            </a>
            <button type="button" onClick={onWatchDemo} className="btn btn-ghost">
              Watch Demo <span style={{ marginLeft: 4 }}>→</span>
            </button>
          </div>
        </div>
        <div className="hero-visual">
          {tweaks.heroVariant === 'imac' ? (
            <div className="imac-wrap">
              <img src="images/imac-screen.png" alt="Roomsy booking calendar on iMac" />
            </div>
          ) : (
            <CalendarPreview />
          )}
          {tweaks.showFloatingStat && (
            <div className="floating-stat review-card">
              <div className="review-row">
                <Stars rating={4.7} size={14} />
                <span className="review-source">Capterra</span>
              </div>
              <div className="review-row">
                <Stars rating={4.7} size={14} />
                <span className="review-source">Software Advice</span>
              </div>
              <div className="review-foot">4.7 average</div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function VideoModal({ open, onClose }) {
  useEffectA(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 9000,
        background: 'rgba(15,12,28,0.78)',
        backdropFilter: 'blur(6px)',
        WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
        animation: 'roomsyFade 180ms ease-out',
      }}
    >
      <style>{`@keyframes roomsyFade { from { opacity: 0 } to { opacity: 1 } }`}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative',
          width: 'min(1100px, 100%)',
          aspectRatio: '16 / 9',
          background: '#000',
          borderRadius: 16,
          overflow: 'hidden',
          boxShadow: '0 30px 80px -20px rgba(0,0,0,0.6)',
        }}
      >
        <button
          type="button"
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: -44, right: 0,
            width: 36, height: 36, borderRadius: 999,
            background: 'rgba(255,255,255,0.12)',
            color: '#fff', fontSize: 20, lineHeight: 1,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}
        >×</button>
        <iframe
          src="https://fast.wistia.net/embed/iframe/bkn09yxmrp?autoPlay=1&seo=false&videoFoam=false"
          title="Roomsy demo"
          allow="autoplay; fullscreen"
          allowFullScreen
          style={{ width: '100%', height: '100%', border: 0, display: 'block' }}
        />
      </div>
    </div>
  );
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [videoOpen, setVideoOpen] = useStateA(false);

  useEffectA(() => {
    const r = document.documentElement.style;
    r.setProperty('--accent', tweaks.accent);
    r.setProperty('--paper', tweaks.background);
    r.setProperty('--f-display', `"${tweaks.displayFont}", serif`);
    r.setProperty('--f-sans', `"${tweaks.bodyFont}", -apple-system, sans-serif`);
  }, [tweaks]);

  return (
    <>
      <Nav />
      <Hero tweaks={tweaks} onWatchDemo={() => setVideoOpen(true)} />
      <VideoModal open={videoOpen} onClose={() => setVideoOpen(false)} />
      <Testimonials />
      <BuiltFor />
      <Features />
      <OtaStrip />
      <FAQ />
      <CtaBanner />
      <Footer />

      <TweaksPanel title="Tweaks" defaultOpen={false}>
        <TweakSection title="Color">
          <TweakRadio label="Accent" value={tweaks.accent} options={ACCENT_OPTIONS} onChange={(v) => setTweak('accent', v)} />
          <TweakRadio label="Background" value={tweaks.background} options={BG_OPTIONS} onChange={(v) => setTweak('background', v)} />
        </TweakSection>
        <TweakSection title="Typography">
          <TweakSelect label="Display font" value={tweaks.displayFont} options={DISPLAY_FONTS} onChange={(v) => setTweak('displayFont', v)} />
          <TweakSelect label="Body font" value={tweaks.bodyFont} options={BODY_FONTS} onChange={(v) => setTweak('bodyFont', v)} />
        </TweakSection>
        <TweakSection title="Hero">
          <TweakRadio label="Background" value={tweaks.heroBackground} options={[{label:'Aurora', value:'aurora'},{label:'Paper', value:'paper'}]} onChange={(v) => setTweak('heroBackground', v)} />
          <TweakToggle label="Review badge" value={tweaks.showFloatingStat} onChange={(v) => setTweak('showFloatingStat', v)} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
