// TeaserHome.jsx — Public-facing marketing homepage with access-code login gate.
// Reads customisable copy from localStorage['td_tweaks'] (set via /dashboard.html).
// Exported as window.TeaserHome for the SPA router.

(function () {
  const { useState: useSt, useEffect: useEff, useRef: useRf } = React;

  // Default teaser content — overridden by dashboard tweaks in localStorage.
  const DEFAULTS = {
    heroEyebrow: 'The Michelin Guide for dental care',
    heroTitle: 'The verified standard\nfor dental care.',
    heroSubline: 'Outcomes, not opinions.',
    heroBody: 'TheDentist.ai gives patients structured, independent information — transparent cost context, AI-powered triage, and matched dentists measured on nine performance axes. No paid placement. No punishment tiers.',
    cta1Label: 'Start your smile audit',
    cta2Label: 'For dental practices',
    feat1Title: 'SmileCam',
    feat1Body: 'Capture your smile, map your concerns, and build a personal dental folio. Patient self-triage or chairside with your dentist.',
    feat2Title: 'AI Triage',
    feat2Body: 'A 90-second swipe-style flow surfaces likely conditions, timely windows, and what-if-untreated context — framed as possibilities to confirm with a licensed dentist.',
    feat3Title: 'Verified Performance',
    feat3Body: 'Nine-axis recognition: Anxious-Friendly, Family-Friendly, Budget-Conscious, Multilingual, Cosmetic Dentistry, Biologic & Holistic, and more — earned, never purchased.',
    practiceEyebrow: 'Dentist Apprentice OS',
    practiceTitle: 'The AI-native operating system for dental practices.',
    practiceBody: 'Twenty agents across three tiers — Basic, Pro, and Clinical OS — automate insurance verification, patient intake, hygiene recall, claims, and revenue analytics. HITL-reviewed, SB 1120-compliant.',
    footerTagline: 'Our experience is the product. AI is the amplifier.',
    accessLabel: 'Early access',
    accessPlaceholder: 'Enter your access code',
    accessCta: 'Unlock access',
  };

  function getTweaks() {
    try {
      const raw = localStorage.getItem('td_tweaks');
      return raw ? { ...DEFAULTS, ...JSON.parse(raw) } : DEFAULTS;
    } catch { return DEFAULTS; }
  }

  // Inline SVG tooth logo
  function ToothLogo({ size = 28, color = 'currentColor' }) {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
        stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 5.5c-1.6-1.5-3.4-2-5.2-1.6C4 4.4 2 6.7 2 9.6c0 2.9 1 4.9 1.5 7.9.3 1.7.5 3 1.5 3s1.6-1.5 2.1-3c.6-1.9 1-3 2.9-3s2.3 1.1 2.9 3c.5 1.5 1.1 3 2.1 3s1.2-1.3 1.5-3c.5-3 1.5-5 1.5-7.9 0-2.9-2-5.2-4.8-5.7-1.8-.4-3.6.1-5.2 1.6Z"/>
      </svg>
    );
  }

  // Access code login modal
  function LoginModal({ onSuccess, onClose }) {
    const [code, setCode] = useSt('');
    const [err, setErr] = useSt('');
    const [loading, setLoading] = useSt(false);
    const inputRef = useRf(null);
    const t = getTweaks();

    useEff(() => { inputRef.current?.focus(); }, []);

    const handleSubmit = async (e) => {
      e.preventDefault();
      if (!code.trim()) return;
      setLoading(true);
      setErr('');

      try {
        // Try the Pages Function first; fall back to local validation.
        let role = null;
        try {
          const res = await fetch('/api/verify-code', {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify({ code: code.trim() }),
          });
          if (res.ok) {
            const data = await res.json();
            if (data.ok) role = data.role;
          }
        } catch (_) {
          // Network error / function not deployed — fall back to client-side env codes.
          const c = code.trim().toUpperCase();
          if (c === 'DENTIST2026') role = 'member';
          if (c === 'ADMIN2026') role = 'admin';
        }

        if (role) {
          try {
            localStorage.setItem('td_access', role);
            localStorage.setItem('td_access_ts', Date.now().toString());
          } catch (_) {}
          onSuccess(role);
        } else {
          setErr('Code not recognised. Check your invite and try again.');
        }
      } catch (ex) {
        setErr('Something went wrong. Please try again.');
      } finally {
        setLoading(false);
      }
    };

    // Trap focus inside modal
    useEff(() => {
      const handler = (e) => {
        if (e.key === 'Escape') onClose();
      };
      document.addEventListener('keydown', handler);
      return () => document.removeEventListener('keydown', handler);
    }, []);

    return (
      <div style={{
        position:'fixed', inset:0, zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center',
        background:'rgba(10,31,51,0.72)', backdropFilter:'blur(4px)',
      }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div style={{
          background:'#FAF8F4', borderRadius:16, padding:'36px 32px', width:'100%', maxWidth:400,
          boxShadow:'0 24px 64px rgba(10,31,51,0.3)', position:'relative',
          fontFamily:'"Inter","Söhne",system-ui,sans-serif',
        }}>
          <button onClick={onClose} style={{
            position:'absolute', top:16, right:16, background:'none', border:'none', cursor:'pointer',
            color:'#6B7E8C', padding:4, fontSize:18, lineHeight:1,
          }}>✕</button>

          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:20 }}>
            <ToothLogo size={22} color="#0A1F33"/>
            <span style={{ fontFamily:'"Source Serif 4",Georgia,serif', fontSize:16, fontWeight:500, color:'#0A1F33' }}>
              TheDentist.ai
            </span>
          </div>

          <h2 style={{ margin:'0 0 6px', fontSize:22, fontFamily:'"Source Serif 4",Georgia,serif', color:'#0A1F33', fontWeight:500 }}>
            {t.accessLabel}
          </h2>
          <p style={{ margin:'0 0 20px', fontSize:14, color:'#6B7E8C', lineHeight:1.5 }}>
            This product is in early access. Enter the code from your invitation to continue.
          </p>

          <form onSubmit={handleSubmit}>
            <input
              ref={inputRef}
              type="text"
              value={code}
              onChange={e => { setCode(e.target.value); setErr(''); }}
              placeholder={t.accessPlaceholder}
              autoComplete="off"
              style={{
                width:'100%', padding:'13px 14px', fontSize:15,
                border:'1.5px solid ' + (err ? '#B8492C' : 'rgba(10,31,51,0.12)'),
                borderRadius:8, fontFamily:'inherit', color:'#0A1F33',
                background:'#fff', outline:'none', boxSizing:'border-box',
                marginBottom: err ? 8 : 16, letterSpacing:'0.04em',
                transition:'border-color 0.15s',
              }}
            />
            {err && (
              <p style={{ margin:'0 0 14px', fontSize:13, color:'#B8492C', lineHeight:1.4 }}>{err}</p>
            )}
            <button type="submit" disabled={loading || !code.trim()} style={{
              width:'100%', padding:'13px', fontSize:15, fontWeight:600,
              background: loading ? '#6B7E8C' : '#0A1F33', color:'#FAF8F4',
              border:'none', borderRadius:8, cursor: loading ? 'default' : 'pointer',
              fontFamily:'inherit', transition:'background 0.15s',
            }}>
              {loading ? 'Checking…' : t.accessCta}
            </button>
          </form>

          <p style={{ marginTop:16, fontSize:12, color:'#9AA8B2', textAlign:'center', lineHeight:1.4 }}>
            Don't have a code? <a href="mailto:hello@thedentist.ai" style={{ color:'#34556B' }}>Request access</a>
          </p>
        </div>
      </div>
    );
  }

  // Feature card
  function FeatureCard({ icon, title, body }) {
    return (
      <div style={{
        background:'#FAF8F4', border:'0.5px solid rgba(10,31,51,0.08)',
        borderRadius:12, padding:'28px 24px',
      }}>
        <div style={{ fontSize:24, marginBottom:14 }}>{icon}</div>
        <h3 style={{
          margin:'0 0 10px', fontSize:17,
          fontFamily:'"Source Serif 4",Georgia,serif', fontWeight:500, color:'#0A1F33',
        }}>{title}</h3>
        <p style={{ margin:0, fontSize:14, color:'#34556B', lineHeight:1.6 }}>{body}</p>
      </div>
    );
  }

  // Recognition axis pill
  function Axis({ label }) {
    return (
      <span style={{
        display:'inline-flex', alignItems:'center', gap:5,
        padding:'5px 12px', borderRadius:999, fontSize:12, fontWeight:500,
        background:'#F2EEE6', color:'#0A1F33', border:'0.5px solid rgba(10,31,51,0.08)',
      }}>
        <span style={{ width:6, height:6, borderRadius:'50%', background:'#C8A862', display:'inline-block' }}/>
        {label}
      </span>
    );
  }

  function TeaserHome({ go }) {
    const [showLogin, setShowLogin] = useSt(false);
    const t = getTweaks();

    // Check if already authenticated
    useEff(() => {
      try {
        const access = localStorage.getItem('td_access');
        if (access === 'admin' || access === 'member') {
          // Already logged in — don't auto-redirect, let them see the homepage
        }
      } catch (_) {}
    }, []);

    const handleSuccess = (role) => {
      setShowLogin(false);
      if (role === 'admin') {
        // Show dashboard link, navigate to app
        go && go('patient-router');
      } else {
        go && go('patient-router');
      }
    };

    const alreadyIn = (() => {
      try { const a = localStorage.getItem('td_access'); return a === 'admin' || a === 'member'; } catch { return false; }
    })();
    const isAdmin = (() => {
      try { return localStorage.getItem('td_access') === 'admin'; } catch { return false; }
    })();

    const heroLines = t.heroTitle.split('\n');

    return (
      <div style={{ fontFamily:'"Inter","Söhne",system-ui,sans-serif', background:'#FAF8F4', minHeight:'100vh' }}>

        {/* ===== Masthead ===== */}
        <header style={{
          background:'#0A1F33', borderBottom:'0.5px solid rgba(250,248,244,0.08)',
          padding:'0 clamp(20px,5vw,60px)', display:'flex', alignItems:'center',
          justifyContent:'space-between', height:60, position:'sticky', top:0, zIndex:100,
        }}>
          <a href="/" style={{ display:'flex', alignItems:'center', gap:10, textDecoration:'none' }}>
            <ToothLogo size={22} color="#FAF8F4"/>
            <span style={{ fontFamily:'"Source Serif 4",Georgia,serif', fontSize:19, fontWeight:500, color:'#FAF8F4', letterSpacing:'-0.01em' }}>
              TheDentist.ai
            </span>
          </a>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            {isAdmin && (
              <a href="/dashboard.html" style={{
                fontSize:12, color:'rgba(250,248,244,0.5)', textDecoration:'none',
                padding:'5px 10px', border:'0.5px solid rgba(250,248,244,0.15)', borderRadius:6,
              }}>
                Dashboard
              </a>
            )}
            {alreadyIn ? (
              <button onClick={() => go && go('patient-router')} style={{
                background:'#B8492C', color:'#FAF8F4', border:'none', borderRadius:8,
                padding:'8px 18px', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
              }}>
                Open app →
              </button>
            ) : (
              <button onClick={() => setShowLogin(true)} style={{
                background:'transparent', color:'rgba(250,248,244,0.8)',
                border:'0.5px solid rgba(250,248,244,0.25)', borderRadius:8,
                padding:'8px 18px', fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:'inherit',
              }}>
                Login
              </button>
            )}
          </div>
        </header>

        {/* ===== Hero ===== */}
        <section style={{
          background:'#0A1F33', padding:'80px clamp(20px,5vw,60px) 90px',
          borderBottom:'1px solid rgba(250,248,244,0.06)',
        }}>
          <div style={{ maxWidth:900, margin:'0 auto' }}>
            <div style={{
              fontSize:12, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase',
              color:'rgba(250,248,244,0.45)', marginBottom:24,
            }}>
              {t.heroEyebrow}
            </div>

            <h1 style={{
              fontFamily:'"Source Serif 4",Georgia,serif',
              fontSize:'clamp(38px,6vw,72px)', lineHeight:1.04,
              fontWeight:500, color:'#FAF8F4',
              margin:'0 0 20px', letterSpacing:'-0.02em',
            }}>
              {heroLines.map((line, i) => (
                <span key={i} style={{ display:'block' }}>
                  {i === heroLines.length - 1 ? (
                    <><span style={{ color:'#B8492C' }}>{line.replace('dental care.','')}</span>
                    <span>dental care.</span></>
                  ) : line}
                </span>
              ))}
            </h1>

            <div style={{
              fontSize:'clamp(16px,2vw,20px)', fontFamily:'"Source Serif 4",Georgia,serif',
              color:'rgba(250,248,244,0.55)', fontStyle:'italic', marginBottom:24,
            }}>
              {t.heroSubline}
            </div>

            <p style={{
              fontSize:16, color:'rgba(250,248,244,0.65)', lineHeight:1.7,
              maxWidth:600, margin:'0 0 40px',
            }}>
              {t.heroBody}
            </p>

            <div style={{ display:'flex', gap:12, flexWrap:'wrap' }}>
              <button onClick={() => alreadyIn ? (go && go('patient-router')) : setShowLogin(true)} style={{
                background:'#B8492C', color:'#FAF8F4', border:'none', borderRadius:8,
                padding:'14px 28px', fontSize:15, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                letterSpacing:'-0.01em',
              }}>
                {alreadyIn ? 'Open app' : t.cta1Label}
              </button>
              <button onClick={() => alreadyIn ? (go && go('patient-router')) : setShowLogin(true)} style={{
                background:'transparent', color:'rgba(250,248,244,0.7)',
                border:'0.5px solid rgba(250,248,244,0.2)', borderRadius:8,
                padding:'14px 28px', fontSize:15, fontWeight:500, cursor:'pointer', fontFamily:'inherit',
              }}>
                {t.cta2Label}
              </button>
            </div>
          </div>
        </section>

        {/* ===== Trust strip ===== */}
        <div style={{
          background:'#F2EEE6', borderBottom:'0.5px solid rgba(10,31,51,0.06)',
          padding:'14px clamp(20px,5vw,60px)',
          display:'flex', flexWrap:'wrap', gap:8, alignItems:'center',
        }}>
          <span style={{ fontSize:12, color:'#6B7E8C', marginRight:8 }}>Recognition axes:</span>
          {['Anxious-Friendly','Family-Friendly','Budget-Conscious','Multilingual','Cosmetic Dentistry','Biologic & Holistic','Patient Favorite'].map(a => (
            <Axis key={a} label={a}/>
          ))}
        </div>

        {/* ===== Features ===== */}
        <section style={{ padding:'72px clamp(20px,5vw,60px)', maxWidth:1120, margin:'0 auto' }}>
          <div style={{
            fontSize:12, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase',
            color:'#9AA8B2', marginBottom:12,
          }}>
            What it does
          </div>
          <h2 style={{
            fontFamily:'"Source Serif 4",Georgia,serif',
            fontSize:'clamp(24px,3.5vw,38px)', fontWeight:500, color:'#0A1F33',
            margin:'0 0 40px', letterSpacing:'-0.01em',
          }}>
            Information first. Verified always.
          </h2>

          <div style={{
            display:'grid',
            gridTemplateColumns:'repeat(auto-fit,minmax(280px,1fr))',
            gap:20,
          }}>
            <FeatureCard
              icon="📷"
              title={t.feat1Title}
              body={t.feat1Body}
            />
            <FeatureCard
              icon="🦷"
              title={t.feat2Title}
              body={t.feat2Body}
            />
            <FeatureCard
              icon="✦"
              title={t.feat3Title}
              body={t.feat3Body}
            />
          </div>
        </section>

        {/* ===== Dentist OS ===== */}
        <section style={{
          background:'#0A1F33', padding:'72px clamp(20px,5vw,60px)',
        }}>
          <div style={{ maxWidth:900, margin:'0 auto' }}>
            <div style={{
              fontSize:12, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase',
              color:'rgba(250,248,244,0.35)', marginBottom:16,
            }}>
              {t.practiceEyebrow}
            </div>
            <h2 style={{
              fontFamily:'"Source Serif 4",Georgia,serif',
              fontSize:'clamp(24px,3.5vw,42px)', fontWeight:500, color:'#FAF8F4',
              margin:'0 0 16px', letterSpacing:'-0.01em', maxWidth:700,
            }}>
              {t.practiceTitle}
            </h2>
            <p style={{ fontSize:16, color:'rgba(250,248,244,0.55)', lineHeight:1.7, maxWidth:580, margin:'0 0 36px' }}>
              {t.practiceBody}
            </p>

            <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
              {[
                'AI Insurance Verification','AI Patient Intake','AI Hygiene Recall',
                'AI Claim Submission','AI Treatment Planner','AI Revenue Analytics',
              ].map(a => (
                <span key={a} style={{
                  padding:'5px 12px', borderRadius:999, fontSize:12, fontWeight:500,
                  background:'rgba(250,248,244,0.06)', color:'rgba(250,248,244,0.55)',
                  border:'0.5px solid rgba(250,248,244,0.1)',
                }}>{a}</span>
              ))}
              <span style={{
                padding:'5px 12px', borderRadius:999, fontSize:12, fontWeight:500,
                background:'rgba(250,248,244,0.06)', color:'rgba(250,248,244,0.4)',
                border:'0.5px solid rgba(250,248,244,0.08)',
              }}>+14 more</span>
            </div>

            <button onClick={() => alreadyIn ? (go && go('patient-router')) : setShowLogin(true)} style={{
              marginTop:36, background:'rgba(250,248,244,0.08)',
              color:'rgba(250,248,244,0.8)', border:'0.5px solid rgba(250,248,244,0.15)',
              borderRadius:8, padding:'12px 24px', fontSize:14, fontWeight:500,
              cursor:'pointer', fontFamily:'inherit',
            }}>
              Learn more about Apprentice OS →
            </button>
          </div>
        </section>

        {/* ===== Access CTA ===== */}
        {!alreadyIn && (
          <section style={{
            padding:'72px clamp(20px,5vw,60px)',
            background:'#F2EEE6', textAlign:'center',
          }}>
            <div style={{ maxWidth:560, margin:'0 auto' }}>
              <div style={{
                fontSize:12, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase',
                color:'#9AA8B2', marginBottom:16,
              }}>
                Early access
              </div>
              <h2 style={{
                fontFamily:'"Source Serif 4",Georgia,serif',
                fontSize:'clamp(22px,3vw,34px)', fontWeight:500, color:'#0A1F33',
                margin:'0 0 14px', letterSpacing:'-0.01em',
              }}>
                We're building in public.
              </h2>
              <p style={{ fontSize:15, color:'#34556B', lineHeight:1.7, margin:'0 0 28px' }}>
                TheDentist.ai is in active development. Access is invite-only while we refine the product. If you have an access code, unlock it below.
              </p>
              <button onClick={() => setShowLogin(true)} style={{
                background:'#0A1F33', color:'#FAF8F4', border:'none', borderRadius:8,
                padding:'14px 32px', fontSize:15, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
              }}>
                Enter access code
              </button>
              <p style={{ marginTop:14, fontSize:13, color:'#9AA8B2' }}>
                Don't have one? <a href="mailto:hello@thedentist.ai" style={{ color:'#34556B', textDecoration:'none' }}>Request an invite</a>
              </p>
            </div>
          </section>
        )}

        {/* ===== Footer ===== */}
        <footer style={{
          padding:'32px clamp(20px,5vw,60px)',
          background:'#0A1F33', borderTop:'0.5px solid rgba(250,248,244,0.06)',
          display:'flex', flexWrap:'wrap', alignItems:'center', justifyContent:'space-between', gap:16,
        }}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <ToothLogo size={18} color="rgba(250,248,244,0.4)"/>
            <span style={{ fontSize:13, color:'rgba(250,248,244,0.35)', fontFamily:'"Source Serif 4",Georgia,serif' }}>
              TheDentist.ai
            </span>
          </div>
          <p style={{ margin:0, fontSize:12, color:'rgba(250,248,244,0.3)', fontStyle:'italic' }}>
            {t.footerTagline}
          </p>
          <div style={{ display:'flex', gap:16 }}>
            {[['Methodology','/methodology/'],['Privacy','/privacy/'],['For Dentists','/for-dentists/']].map(([l,h]) => (
              <a key={l} href={h} style={{ fontSize:12, color:'rgba(250,248,244,0.35)', textDecoration:'none' }}>{l}</a>
            ))}
          </div>
        </footer>

        {/* ===== Login modal ===== */}
        {showLogin && (
          <LoginModal onSuccess={handleSuccess} onClose={() => setShowLogin(false)}/>
        )}
      </div>
    );
  }

  window.TeaserHome = TeaserHome;
})();
