// app.jsx — React islands: iOS modal, phone carousel, ticker, audio player, screenshot slider

const { useState } = React;

// ── iOS waitlist modal ────────────────────────────────────

function IosModal({ onClose }) {
  const [email, setEmail] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Something went wrong');
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <span className="mdi">close</span>
        </button>
        <div className="modal-eyebrow">
          <AppleIcon />
          Coming soon
        </div>
        <h2 className="modal-title">
          Get notified when iOS is ready<span className="dot"></span>
        </h2>
        <p className="modal-sub">We're working on the iOS version. Drop your email and we'll let you know the moment it's live.</p>
        {submitted ? (
          <div className="modal-success">
            <span className="mdi-fill" style={{ fontSize: 44, color: 'var(--primary)', lineHeight: 1 }}>check_circle</span>
            <h3>You're on the list<span className="dot"></span></h3>
            <p>We'll notify you as soon as iOS is available.</p>
          </div>
        ) : (
          <form className="modal-form" onSubmit={handleSubmit}>
            <input
              type="email"
              placeholder="your@email.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="modal-input"
            />
            {error && (
              <p style={{ fontSize: 13, color: '#e53e3e', fontFamily: 'var(--font-sans)', margin: '0 0 4px' }}>{error}</p>
            )}
            <button type="submit" className="btn btn-dark" style={{ width: '100%', justifyContent: 'center', padding: '16px 24px' }} disabled={loading}>
              {loading ? 'Sending…' : 'Notify me'}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

// Host component — exposes openIos globally so static HTML buttons can trigger it
function IosModalHost() {
  const [show, setShow] = useState(false);

  React.useEffect(() => {
    window._venturer = { openIos: () => setShow(true) };
    return () => { window._venturer = null; };
  }, []);

  return show ? <IosModal onClose={() => setShow(false)} /> : null;
}

// ── Mount all islands ─────────────────────────────────────

function mount() {
  const $ = (id) => document.getElementById(id);

  // iOS modal (portal — renders outside the content flow)
  const modalEl = $('root-ios-modal');
  if (modalEl) ReactDOM.createRoot(modalEl).render(<IosModalHost />);

  // Hero phone carousel
  const carouselEl = $('root-hero-carousel');
  if (carouselEl) ReactDOM.createRoot(carouselEl).render(<HeroPhoneCarousel />);

  // City ticker
  const tickerEl = $('root-ticker');
  if (tickerEl) ReactDOM.createRoot(tickerEl).render(<Ticker />);

  // Audio player card (just the card — heading/text is static HTML above)
  const audioEl = $('root-audio-player');
  if (audioEl) ReactDOM.createRoot(audioEl).render(<AudioPlayerCard />);

  // Screenshot slider (just the slider — heading is static HTML above)
  const screenshotsEl = $('root-screenshots');
  if (screenshotsEl) ReactDOM.createRoot(screenshotsEl).render(<AppScreenshotsSlider />);
}

// Wait for fonts before mounting so icons and headings render correctly
const fontJobs = [
  document.fonts.load('24px "Material Symbols Rounded"'),
  document.fonts.load('24px "Material Symbols Rounded Fill"'),
  document.fonts.load('400 48px "TypnicHeadline"'),
];
let mounted = false;
const go = () => { if (!mounted) { mounted = true; mount(); } };
Promise.all(fontJobs).then(go).catch(go);
setTimeout(go, 1500);
