// Love Costs Nothing — app shell
// Parisian stationery aesthetic. All screens + nav live here.

const { useState, useEffect, useRef, useMemo } = React;

// ─────────────────────────────────────────────
// Default tweakable values (host rewrites this block)
// ─────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "letterTitle": "For you, my love.",
  "letterBody": "To my dearest sweetheart.\n\nI always sit and think to myself of how much you blow my mind. I love you and will say it every single chance I get because I really mean it and you give me the best feeling in the world.\n\nI'm really glad you are in my life and I will dedicate my time to show you the true meaning of love.\n\nThe feeling I get from you is just out of this universe and I want that feeling always and forever. You are always on my mind — I don't even try to get you off my mind, because I love it when you're on it. That is the best feeling ever.\n\nEvery moment just feels magical.\n\nYou are literally my number one. I don't want anyone else besides you.\n\nI've got a little fantasy that plays in my head where we have a little moment… in a perfect sunset, with Shekhinah 'Steady Pt. 2' playing in the background.\n\nEverything feels calm, like time stopped for a little bit… and I'm just there, looking at you, feeling like I don't want the moment to end.\n\nAnd in this moment… I'd really like to kiss your gorgeous lips for the first time.",
  "letterSignature": "Yours, always — Dexter",
  "motionIntensity": "cinematic"
}/*EDITMODE-END*/;

// Motion intensity multipliers
const MOTION = {
  whisper:   { base: 1.4, scale: 0.6 },
  cinematic: { base: 1.0, scale: 1.0 },
  rich:      { base: 0.8, scale: 1.3 },
};

// ─────────────────────────────────────────────
// Shared visual constants
// ─────────────────────────────────────────────
// Dynamic Theme mapped to CSS Variables defined in index.html
const PAPER = 'var(--bg)';
const PAPER_DEEP = 'var(--bg-alt)';
const INK = 'var(--text-main)';
const ROSE = 'var(--wax)';
const ROSE_SOFT = 'var(--text-sec)'; // previously C3A2A4
const BLUSH = 'var(--accent)';
const GOLD = 'var(--gold)';
const MUTED = 'var(--muted)';

const serif = "'Cormorant Garamond', 'Playfair Display', Georgia, serif";
const serifDisplay = "'Playfair Display', 'Cormorant Garamond', Georgia, serif";
const sans = "'Inter', -apple-system, system-ui, sans-serif";
const script = "'Pinyon Script', 'Dancing Script', cursive";

// ─────────────────────────────────────────────
// Tiny icons (hairline)
// ─────────────────────────────────────────────
const Icon = {
  envelope: (c = INK) => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <rect x="2.5" y="5" width="17" height="12" rx="1" stroke={c} strokeWidth="1"/>
      <path d="M2.5 6l8.5 6 8.5-6" stroke={c} strokeWidth="1" strokeLinecap="round"/>
    </svg>
  ),
  frame: (c = INK) => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <rect x="3" y="3" width="16" height="16" rx="1" stroke={c} strokeWidth="1"/>
      <circle cx="8" cy="9" r="1.3" stroke={c} strokeWidth="1"/>
      <path d="M3 15l4.5-4 4 3.5 3-2.5L19 15" stroke={c} strokeWidth="1" strokeLinejoin="round"/>
    </svg>
  ),
  book: (c = INK) => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <path d="M4 4.5h6.5c.8 0 1.5.7 1.5 1.5v12H5.5c-.8 0-1.5-.7-1.5-1.5V4.5z" stroke={c} strokeWidth="1"/>
      <path d="M18 4.5h-6.5c-.8 0-1.5.7-1.5 1.5v12h7c.8 0 1.5-.7 1.5-1.5V6c0-.8-.7-1.5-1.5-1.5z" stroke={c} strokeWidth="1"/>
    </svg>
  ),
  heart: (c = INK, filled = false) => (
    <svg width="22" height="22" viewBox="0 0 22 22" fill={filled ? c : 'none'}>
      <path d="M11 18.5s-7-4.2-7-9.3c0-2.3 1.7-4.2 4-4.2 1.5 0 2.5.9 3 1.8.5-.9 1.5-1.8 3-1.8 2.3 0 4 1.9 4 4.2 0 5.1-7 9.3-7 9.3z" stroke={c} strokeWidth="1"/>
    </svg>
  ),
  chevron: (c = INK, dir = 'right') => (
    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" style={{ transform: dir === 'left' ? 'rotate(180deg)' : undefined }}>
      <path d="M4 2l4 4-4 4" stroke={c} strokeWidth="1.2" fill="none" strokeLinecap="round"/>
    </svg>
  ),
};

// ─────────────────────────────────────────────
// App root
// ─────────────────────────────────────────────
// ─────────────────────────────────────────────
// Reader Gate (Authentication)
// ─────────────────────────────────────────────
function ReaderGate({ onLogin }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!window.BetweenUsBackend?.isConfigured) return;
    setLoading(true);
    setError(null);
    const { error: signInError } = await window.BetweenUsBackend.signInWithPassword(email, password);
    if (signInError) {
      if (signInError.message.includes('Invalid login credentials')) {
        const { error: signUpError } = await window.BetweenUsBackend.signUpWithPassword(email, password);
        if (signUpError) {
          setError(signUpError.message);
          setLoading(false);
        } else {
          onLogin();
        }
      } else {
        setError(signInError.message);
        setLoading(false);
      }
    } else {
      onLogin();
    }
  }

  return (
    <div className="gate-overlay">
      <div className="gate-card">
        <div style={{ fontFamily: sans, fontSize: 13, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 8, color: 'rgba(255,255,255,0.6)' }}>Private access</div>
        <h1 style={{ fontFamily: serifDisplay, fontStyle: 'italic', fontSize: 28, margin: '0 0 12px 0', fontWeight: 500 }}>Shared Space</h1>
        <p style={{ fontFamily: sans, fontSize: 14, color: 'rgba(255,255,255,0.7)', margin: 0, lineHeight: 1.5 }}>
          This space is just for us. Enter your email and password to get in.
        </p>
        <form onSubmit={handleSubmit} style={{ marginTop: 24, textAlign: 'left' }}>
          <label style={{ fontFamily: sans, fontSize: 12, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: 1 }}>Email</label>
          <input type="email" required className="gate-input" placeholder="you@example.com" value={email} onChange={e => setEmail(e.target.value)} />
          
          <div style={{ marginTop: 16 }}>
            <label style={{ fontFamily: sans, fontSize: 12, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: 1 }}>Password</label>
            <input type="password" required className="gate-input" placeholder="Your password" value={password} onChange={e => setPassword(e.target.value)} />
          </div>

          {error && <div style={{ color: '#ff6b6b', fontSize: 13, marginTop: 12, fontFamily: sans }}>{error}</div>}

          <button type="submit" disabled={loading} className="gate-btn">
            {loading ? 'Unlocking...' : 'Enter'}
          </button>
        </form>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// App root
// ─────────────────────────────────────────────
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = useState('home'); // home | letter | letters | gallery | story
  const [letterStage, setLetterStage] = useState(0); // 0 sealed, 1 cracked, 2 unfolded, 3 reading
  const [activeLetter, setActiveLetter] = useState(null);
  const motion = MOTION[tweaks.motionIntensity] || MOTION.cinematic;
  
  // Theme state
  const [theme, setTheme] = useState('dark');
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);
  
  // App state
  const [isReady, setIsReady] = useState(false);
  const [authChecked, setAuthChecked] = useState(false);
  const [authenticated, setAuthenticated] = useState(false);
  const [backendData, setBackendData] = useState({ letters: [], memories: [], gallery: [], plans: [] });

  // Initialize auth and backend
  useEffect(() => {
    async function init() {
      if (!window.BetweenUsBackend?.isConfigured) {
        setAuthChecked(true);
        setAuthenticated(true);
        setIsReady(true);
        return;
      }
      try {
        const { data: { session } } = await window.BetweenUsBackend.getSession();
        setAuthenticated(true);
        fetchData();
      } catch (e) {
        console.error("Auth check failed", e);
      } finally {
        setAuthChecked(true);
      }
    }
    init();

    if (window.BetweenUsBackend?.onAuthChange) {
      window.BetweenUsBackend.onAuthChange((event, session) => {
        if (session) {
          setAuthenticated(true);
          fetchData();
        } else {
          setAuthenticated(false);
        }
      });
    }
  }, []);

  async function fetchData() {
    if (!window.BetweenUsBackend) return;
    try {
      const data = await window.BetweenUsBackend.fetchPublicContent();
      setBackendData(data);
    } catch (e) {
      console.error("Failed fetching data", e);
    } finally {
      setIsReady(true);
    }
  }

  // Reset letter state when leaving the letter flow
  useEffect(() => {
    if (screen !== 'letter') {
      setLetterStage(0);
      setActiveLetter(null);
    }
  }, [screen]);

  if (!authChecked) return null;
  // temporarily disabled login 
  // if (!authenticated && window.BetweenUsBackend?.requireReaderLogin) {
  //   return <ReaderGate onLogin={() => setAuthenticated(true)} />;
  // }
  if (!isReady) return null;

  const featuredLetter = backendData.letters.find(l => l.status === 'unread') || backendData.letters[0];

  return (
    <>
      <IOSDevice width={402} height={874} disableConstraints={true}>
        <div style={{
          position: 'absolute', inset: 0,
          background: `radial-gradient(130% 90% at 50% 0%, #EEEFF3 0%, ${PAPER} 55%, ${PAPER_DEEP} 100%)`,
          overflow: 'hidden',
        }}>
          {/* Paper grain */}
          <PaperGrain />

          {/* Screens */}
          <ScreenFrame active={screen === 'home'} motion={motion}>
            <HomeScreen 
              onOpenLetter={() => { 
                setActiveLetter(featuredLetter); 
                setScreen('letter'); 
                setLetterStage(0); 
              }} 
              tweaks={tweaks} 
              featuredLetter={featuredLetter}
            />
          </ScreenFrame>

          <ScreenFrame active={screen === 'letter'} motion={motion}>
            <LetterScreen
              stage={letterStage}
              setStage={setLetterStage}
              letter={activeLetter}
              tweaks={tweaks}
              motion={motion}
              onClose={() => setScreen('home')}
            />
          </ScreenFrame>

          <ScreenFrame active={screen === 'letters'} motion={motion}>
            <LettersScreen 
              letters={backendData.letters} 
              onOpen={(clickedLetter) => { 
                setActiveLetter(clickedLetter); 
                setScreen('letter'); 
                setLetterStage(0); 
              }} 
            />
          </ScreenFrame>

          <ScreenFrame active={screen === 'gallery'} motion={motion}>
            <GalleryScreen gallery={backendData.gallery} />
          </ScreenFrame>

          <ScreenFrame active={screen === 'story'} motion={motion}>
            <StoryScreen memories={backendData.memories} />
          </ScreenFrame>

          {/* Bottom nav — hidden during letter reading */}
          <BottomNav
            current={screen}
            onChange={setScreen}
            hidden={screen === 'letter' && letterStage >= 2}
          />
        </div>
      </IOSDevice>

      <TweaksUI tweaks={tweaks} setTweak={setTweak} theme={theme} setTheme={setTheme} />
    </>
  );
}

// ─────────────────────────────────────────────
// Screen frame — crossfade between screens
// ─────────────────────────────────────────────
function ScreenFrame({ active, motion, children }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      opacity: active ? 1 : 0,
      pointerEvents: active ? 'auto' : 'none',
      transition: `opacity ${0.5 * motion.base}s ease`,
      overflow: 'hidden',
    }}>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────
// Paper grain overlay
// ─────────────────────────────────────────────
function PaperGrain() {
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.11  0 0 0 0 0.14  0 0 0 0 0.28  0 0 0 0.06 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>\")",
        opacity: 0.45, mixBlendMode: 'multiply',
      }} />
      {/* vignette */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(120% 80% at 50% 50%, transparent 55%, rgba(20, 26, 58, 0.10) 100%)',
      }} />
    </>
  );
}

// Expose to window so other script tags (if any) can use
Object.assign(window, { App, PAPER, PAPER_DEEP, INK, ROSE, ROSE_SOFT, BLUSH, GOLD, MUTED, serif, serifDisplay, sans, script, Icon });
