/* ============================================================
   Wayfare — Interactive App Preview
   A clickable, phone-style mini-app:
   Plan → Results → Detail → Camera AI → Emergency
   ============================================================ */

const VENUE_DATA = [
  {
    id: 'taj-rambagh',
    type: 'Heritage hotel',
    name: 'Taj Rambagh Palace',
    area: 'Jaipur · Rambagh',
    price: '₹₹₹₹',
    score: 94,
    oneline: 'Step-free entry, 90 cm doorways, palace-side accessible suites verified by Aisha.',
    needs: ['wheelchair', 'vision', 'dietary', 'quiet'],
    accent: '#1F4D3F',
    photo: 'palace',
    verifiedBy: {
      name: 'Aisha Verma',
      photo: window.__resources.avatarAisha,
      tagline: '8-year wheelchair user, hospitality scout · Jaipur native',
      visits: 142,
      cred: ['Wheelchair user', 'Travelled 14 countries', 'Trained hotel auditor'],
    },
    breakdown: [
      { label: 'Entry & navigation', score: 96, note: 'Ramped entry. Lift to all floors. 110 cm clearance corridors.' },
      { label: 'Bedroom & bathroom', score: 92, note: 'Roll-in shower, fold-down bench, grab rails on 3 sides. Bed height 51 cm.' },
      { label: 'Dining & menus', score: 90, note: 'Tactile + braille menu. Vegan, halal, low-FODMAP options.' },
      { label: 'Staff training', score: 95, note: 'All staff trained in disability awareness (Certified, 2024).' },
      { label: 'Sensory & quiet', score: 88, note: 'Quiet wing available. Avg. 38 dB. Dimmable lighting.' },
    ],
  },
  {
    id: 'amer-fort',
    type: 'Attraction',
    name: 'Amer Fort — Accessible Tour',
    area: 'Jaipur · Amer',
    price: 'Free',
    score: 78,
    oneline: 'Motorised buggy route covers 70% of the fort. Some courtyards remain cobbled.',
    needs: ['wheelchair', 'hearing'],
    accent: '#C68B59',
    photo: 'fort',
    verifiedBy: {
      name: 'Rohan Kapoor',
      photo: window.__resources.avatarRohan,
      tagline: 'Heritage tour scout · uses a power chair',
      visits: 64,
      cred: ['Power chair user', 'Certified heritage guide', 'BSL & ISL signing'],
    },
    breakdown: [
      { label: 'Entry & navigation', score: 80, note: 'Buggy access from Jaleb Chowk. Two ramped paths.' },
      { label: 'Facilities', score: 72, note: 'Accessible washroom at base. Companion-care room available.' },
      { label: 'Sensory', score: 82, note: 'Sound & light show offers ISL/BSL interpreters at 7pm slot.' },
    ],
  },
  {
    id: 'anokhi',
    type: 'Café',
    name: 'Anokhi Café',
    area: 'Jaipur · C-Scheme',
    price: '₹₹',
    score: 89,
    oneline: 'Quiet corner, allergen-tagged menu, step-free entry from the side gate.',
    needs: ['quiet', 'dietary', 'wheelchair'],
    accent: '#7BAA80',
    photo: 'cafe',
    verifiedBy: {
      name: 'Maya Iyer',
      photo: window.__resources.avatarMaya,
      tagline: 'Autistic food critic & sensory scout',
      visits: 211,
      cred: ['Autistic adult', 'Certified nutritionist', '2.4k followers'],
    },
    breakdown: [
      { label: 'Sensory', score: 94, note: 'Average 42 dB. No live music. Soft warm lighting.' },
      { label: 'Menu access', score: 90, note: 'Allergen-tagged, photo menu, large-print menu on request.' },
      { label: 'Entry & seating', score: 85, note: 'Side ramp, 80 cm doorway. Two corner tables.' },
    ],
  },
  {
    id: 'ola-mobility',
    type: 'Transport',
    name: 'Ola Mobility — Step-free Cars',
    area: 'Jaipur · Citywide',
    price: '₹',
    score: 82,
    oneline: 'Wheelchair-accessible cabs with trained drivers. 18-min average wait time.',
    needs: ['wheelchair'],
    accent: '#3A7CA5',
    photo: 'transport',
    verifiedBy: {
      name: 'Priya Singh',
      photo: window.__resources.avatarPriya,
      tagline: 'Mobility advocate · wheelchair user since 2014',
      visits: 38,
      cred: ['Manual chair user', 'Cab audit lead'],
    },
    breakdown: [
      { label: 'Vehicle', score: 86, note: 'Side-loading ramp, 4-point tie-down. Tested with 38 cm chair.' },
      { label: 'Driver training', score: 84, note: 'All drivers complete disability-awareness module.' },
      { label: 'Booking flow', score: 78, note: 'Filter in-app. SMS confirmation. Voice-friendly.' },
    ],
  },
];

const NEED_OPTIONS = [
  { key: 'wheelchair', label: 'Wheelchair', icon: 'wheelchair' },
  { key: 'vision', label: 'Low vision', icon: 'vision' },
  { key: 'hearing', label: 'Deaf / HoH', icon: 'hearing' },
  { key: 'cognitive', label: 'Cognitive', icon: 'cognitive' },
  { key: 'dietary', label: 'Dietary', icon: 'dietary' },
  { key: 'quiet', label: 'Quiet / sensory', icon: 'quiet' },
];

/* ----------- Photo placeholder swatches ----------- */
function VenuePhoto({ kind, accent, label, height = 160 }) {
  const patterns = {
    palace: (
      <>
        <rect width="400" height="160" fill="#F2EADB" />
        <path d="M0 130 L40 130 L40 90 L60 90 L60 70 L80 70 L80 40 L100 40 L100 70 L120 70 L120 90 L160 90 L160 60 L180 60 L180 90 L220 90 L220 60 L240 60 L240 90 L280 90 L280 70 L300 70 L300 40 L320 40 L320 70 L340 70 L340 90 L360 90 L360 130 L400 130 L400 160 L0 160 Z" fill={accent} opacity="0.92" />
        <circle cx="320" cy="36" r="14" fill="#F4A261" />
        <path d="M0 130 L400 130 L400 160 L0 160 Z" fill="#1F4D3F" opacity="0.18" />
      </>
    ),
    fort: (
      <>
        <rect width="400" height="160" fill="#F2EADB" />
        <path d="M0 60 L60 30 L120 60 L180 20 L240 60 L300 40 L360 70 L400 50 L400 160 L0 160 Z" fill={accent} opacity="0.92" />
        <path d="M0 90 L80 70 L160 100 L240 80 L320 105 L400 88 L400 160 L0 160 Z" fill="#1F4D3F" opacity="0.32" />
        <circle cx="80" cy="34" r="12" fill="#F4A261" />
      </>
    ),
    cafe: (
      <>
        <rect width="400" height="160" fill="#F2EADB" />
        <circle cx="120" cy="80" r="50" fill={accent} opacity="0.88" />
        <circle cx="280" cy="100" r="36" fill="#1F4D3F" opacity="0.7" />
        <circle cx="220" cy="58" r="24" fill="#F4A261" />
        <rect x="60" y="118" width="280" height="6" fill="#1F4D3F" opacity="0.3" />
      </>
    ),
    transport: (
      <>
        <rect width="400" height="160" fill="#F2EADB" />
        <rect x="40" y="60" width="320" height="60" rx="14" fill={accent} opacity="0.92" />
        <rect x="60" y="70" width="100" height="36" rx="6" fill="#FFFBF0" opacity="0.85" />
        <rect x="180" y="70" width="100" height="36" rx="6" fill="#FFFBF0" opacity="0.85" />
        <circle cx="100" cy="120" r="14" fill="#1F4D3F" />
        <circle cx="300" cy="120" r="14" fill="#1F4D3F" />
        <path d="M310 120 L350 120 L370 140 L310 140 Z" fill="#F4A261" />
      </>
    ),
    city: (
      <>
        <rect width="400" height="160" fill="#F2EADB" />
        <path d="M0 100 L30 100 L30 60 L50 60 L50 100 L80 100 L80 40 L110 40 L110 100 L150 100 L150 70 L180 70 L180 100 L220 100 L220 30 L250 30 L250 100 L290 100 L290 60 L320 60 L320 100 L360 100 L360 80 L400 80 L400 160 L0 160 Z" fill={accent} opacity="0.92" />
        <circle cx="340" cy="30" r="14" fill="#F4A261" />
      </>
    ),
  };
  return (
    <div style={{ position: 'relative', borderRadius: 14, overflow: 'hidden', height }}>
      <svg viewBox="0 0 400 160" preserveAspectRatio="xMidYMid slice" width="100%" height="100%">
        {patterns[kind] || patterns.city}
      </svg>
      {label && (
        <span style={{ position: 'absolute', bottom: 10, left: 10, background: 'rgba(255,255,255,0.94)', color: 'var(--ink)', padding: '4px 10px', borderRadius: 999, fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{label}</span>
      )}
    </div>
  );
}

/* ----------- App: header inside the phone ----------- */
function AppHeader({ title, onBack, right }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 14px',
      borderBottom: '1px solid var(--line)',
      background: 'var(--surface)',
    }}>
      {onBack ? (
        <button onClick={onBack} aria-label="Back" style={{ background: 'transparent', border: 0, fontSize: 18, color: 'var(--ink)' }}>‹</button>
      ) : <Brandmark size={22} />}
      <strong style={{ fontFamily: 'var(--font-serif)', fontWeight: 500, fontSize: 16, flex: 1 }}>{title}</strong>
      {right}
    </div>
  );
}

/* ----------- Screen: Plan ----------- */
function ScreenPlan({ needs, setNeeds, query, setQuery, onSubmit, listening, setListening }) {
  const [typed, setTyped] = useState('');

  useEffect(() => {
    if (!listening) return;
    const phrase = "I'm a wheelchair user going to Jaipur for 3 days in March. Step-free hotels, quiet restaurants.";
    let i = 0;
    const id = setInterval(() => {
      i += 2;
      setTyped(phrase.slice(0, i));
      if (i >= phrase.length) {
        clearInterval(id);
        setQuery(phrase);
        setListening(false);
      }
    }, 50);
    return () => clearInterval(id);
  }, [listening]);

  const toggle = (k) => setNeeds(needs.includes(k) ? needs.filter(n => n !== k) : [...needs, k]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppHeader title="Plan a trip" />
      <div style={{ padding: 16, overflow: 'auto', flex: 1 }}>
        <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, lineHeight: 1.2, marginBottom: 4 }}>Hi Anika.<br/>Where shall we go?</div>
        <p style={{ color: 'var(--muted)', fontSize: 13, marginTop: 4, marginBottom: 16 }}>Tell me about your trip, in your own words.</p>

        <div style={{ background: 'var(--surface)', border: '1.5px solid var(--ink)', borderRadius: 16, padding: 10 }}>
          <textarea
            value={listening ? typed : query}
            onChange={e => setQuery(e.target.value)}
            placeholder="e.g. Jaipur with my dad in March. He uses a wheelchair and prefers quiet places…"
            rows={4}
            style={{ width: '100%', border: 0, background: 'transparent', font: 'inherit', fontSize: 14, resize: 'none', outline: 'none' }}
          />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingTop: 6 }}>
            <button
              onClick={() => setListening(l => !l)}
              aria-label="Voice input"
              style={{
                width: 36, height: 36, borderRadius: 999,
                background: listening ? 'var(--emergency)' : 'var(--ink)', color: '#fff',
                border: 0, display: 'grid', placeItems: 'center',
                animation: listening ? 'pulseRing 1.4s infinite' : 'none',
              }}
            >
              <Icon.mic width="16" height="16" />
            </button>
            {listening && (
              <span className="wave" style={{ height: 20 }}><span /><span /><span /><span /><span /></span>
            )}
            <span style={{ flex: 1 }} />
            <button
              onClick={onSubmit}
              className="btn btn--accent btn--sm"
              disabled={!query.trim() && !listening}
              style={{ opacity: query.trim() ? 1 : 0.5 }}
            >
              Plan <Icon.arrow width="14" height="14" />
            </button>
          </div>
        </div>

        <div style={{ marginTop: 22 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.14em', color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 700, marginBottom: 10 }}>Your accessibility profile</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {NEED_OPTIONS.map(opt => (
              <button
                key={opt.key}
                className="chip"
                aria-pressed={needs.includes(opt.key)}
                onClick={() => toggle(opt.key)}
                style={{ fontSize: 12 }}
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 20, padding: 14, background: 'var(--primary-soft)', borderRadius: 14, fontSize: 12.5, lineHeight: 1.45, color: 'var(--primary-deep)' }}>
          <strong style={{ fontFamily: 'var(--font-serif)', fontSize: 14, display: 'block', marginBottom: 4 }}>Why we ask</strong>
          Your profile stays on your device. Wayfare uses it to filter, not advertise.
        </div>
      </div>
    </div>
  );
}

/* ----------- Screen: Results ----------- */
function ScreenResults({ needs, query, onOpen, onBack, onCamera }) {
  const [planning, setPlanning] = useState(true);
  const [step, setStep] = useState(0);
  const steps = [
    'Parsing needs with Wayfare AI…',
    'Querying 142 verified venues in Jaipur…',
    'Calling Wayfare Score engine…',
    'Cross-checking scout reports…',
    'Composing your itinerary…',
  ];
  useEffect(() => {
    if (!planning) return;
    if (step >= steps.length - 1) {
      const t = setTimeout(() => setPlanning(false), 600);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStep(s => s + 1), 700);
    return () => clearTimeout(t);
  }, [planning, step]);

  if (planning) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <AppHeader title="Building your itinerary" onBack={onBack} />
        <div style={{ padding: 18, flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--primary)', fontWeight: 700, textTransform: 'uppercase' }}>● Wayfare AI</span>
          </div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, lineHeight: 1.2, marginBottom: 18 }}>Planning Jaipur for 3 days…</div>
          <div style={{ display: 'grid', gap: 10 }}>
            {steps.map((s, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                fontSize: 13,
                opacity: i <= step ? 1 : 0.35,
                transition: 'opacity 300ms',
              }}>
                <span style={{
                  width: 18, height: 18, borderRadius: 999,
                  background: i < step ? 'var(--success)' : i === step ? 'var(--accent)' : 'var(--line)',
                  color: '#fff', display: 'grid', placeItems: 'center',
                }}>
                  {i < step ? <Icon.check width="10" height="10" /> : i === step ? <span style={{ width: 6, height: 6, borderRadius: 999, background: '#fff', animation: 'pulseRing 1s infinite' }} /> : null}
                </span>
                <span>{s}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppHeader title="Jaipur · 3 days" onBack={onBack} right={
        <button onClick={onCamera} aria-label="Ask the camera AI" style={{ background: 'var(--ink)', color: '#fff', border: 0, borderRadius: 999, width: 30, height: 30, display: 'grid', placeItems: 'center' }}>
          <Icon.camera width="14" height="14" />
        </button>
      } />
      <div style={{ padding: 14, overflow: 'auto', flex: 1, background: 'var(--bg)' }}>
        <div style={{ background: 'var(--surface-warm)', border: '1.5px solid var(--line)', borderRadius: 14, padding: 12, marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.14em', color: 'var(--primary)', fontWeight: 700, textTransform: 'uppercase' }}>● Wayfare summary</div>
          <p style={{ margin: '6px 0 0', fontSize: 13.5, lineHeight: 1.45 }}>
            Here's a 3-day Jaipur trip tuned to <strong>wheelchair access</strong> and <strong>quiet places</strong>. Every option below was visited by a verified scout. Average Wayfare Score: <strong>87</strong>.
          </p>
        </div>

        <div style={{ display: 'grid', gap: 10 }}>
          {VENUE_DATA.map(v => (
            <button
              key={v.id}
              onClick={() => onOpen(v)}
              style={{
                textAlign: 'left',
                background: 'var(--surface)',
                border: '1.5px solid var(--line)',
                borderRadius: 14,
                padding: 10,
                cursor: 'pointer',
                display: 'block',
              }}
            >
              <VenuePhoto kind={v.photo} accent={v.accent} height={110} label={v.type} />
              <div style={{ padding: '10px 4px 4px' }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                  <strong style={{ fontFamily: 'var(--font-serif)', fontSize: 15.5, fontWeight: 500, flex: 1, lineHeight: 1.2 }}>{v.name}</strong>
                  <ScorePill score={v.score} />
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon.pin width="11" height="11" /> {v.area} · {v.price}
                </div>
                <p style={{ fontSize: 12.5, lineHeight: 1.4, margin: '8px 0 6px', color: 'var(--ink-soft)' }}>{v.oneline}</p>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--primary)' }}>
                  <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--success)' }} />
                  Verified by {v.verifiedBy.name}
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ----------- Screen: Detail ----------- */
function ScreenDetail({ venue, onBack }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'auto' }}>
      <div style={{ position: 'relative' }}>
        <VenuePhoto kind={venue.photo} accent={venue.accent} height={180} />
        <button onClick={onBack} aria-label="Back" style={{ position: 'absolute', top: 12, left: 12, width: 34, height: 34, borderRadius: 999, background: 'rgba(255,255,255,0.95)', border: 0, display: 'grid', placeItems: 'center', fontSize: 18 }}>‹</button>
        <div style={{ position: 'absolute', top: 12, right: 12, background: 'rgba(0,0,0,0.78)', color: '#fff', padding: '6px 12px', borderRadius: 999, fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.1em', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <Icon.shield width="11" height="11" /> Scout verified
        </div>
      </div>
      <div style={{ padding: 16, flex: 1 }}>
        <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.14em', fontWeight: 700 }}>{venue.type}</div>
        <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 500, fontSize: 22, margin: '4px 0 4px', lineHeight: 1.15 }}>{venue.name}</h3>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 6 }}>
          <Icon.pin width="11" height="11" /> {venue.area} · {venue.price}
        </div>

        <div style={{ marginTop: 16, padding: 12, background: 'var(--bg-alt)', borderRadius: 12, display: 'flex', alignItems: 'center', gap: 12 }}>
          <LighthouseScore score={venue.score} size={80} label="" />
          <div>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18 }}>Wayfare Score</div>
            <div style={{ fontSize: 11, color: 'var(--muted)' }}>Based on 8 audited criteria + 142 scout reports</div>
          </div>
        </div>

        {/* Need badges */}
        <div style={{ marginTop: 14, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {venue.needs.map(n => {
            const opt = NEED_OPTIONS.find(o => o.key === n);
            if (!opt) return null;
            return <span key={n} className="chip" style={{ background: 'var(--primary-soft)', borderColor: 'var(--primary)', color: 'var(--primary-deep)', fontSize: 11 }}>{opt.label}</span>;
          })}
        </div>

        {/* Score breakdown */}
        <div style={{ marginTop: 18 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 700, marginBottom: 10 }}>Score breakdown · with evidence</div>
          <div style={{ display: 'grid', gap: 10 }}>
            {venue.breakdown.map(b => (
              <div key={b.label} style={{ display: 'flex', gap: 12, padding: 10, background: 'var(--surface)', border: '1.5px solid var(--line)', borderRadius: 12 }}>
                <div style={{
                  width: 38, height: 38, flexShrink: 0,
                  borderRadius: 8,
                  background: b.score >= 90 ? 'var(--score-A)' : b.score >= 80 ? 'var(--score-B)' : b.score >= 70 ? 'var(--score-C)' : 'var(--score-D)',
                  color: '#fff',
                  fontFamily: 'var(--font-mono)',
                  fontWeight: 700,
                  fontSize: 14,
                  display: 'grid', placeItems: 'center',
                }}>{b.score}</div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 2 }}>{b.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.4 }}>{b.note}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Scout card */}
        <div style={{ marginTop: 18, padding: 14, background: 'var(--ink)', color: 'var(--bg)', borderRadius: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <ScoutAvatar name={venue.verifiedBy.name} photo={venue.verifiedBy.photo} color="var(--accent)" size={50} />
            <div>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontWeight: 500 }}>{venue.verifiedBy.name}</div>
              <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.7)' }}>{venue.verifiedBy.tagline}</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 12 }}>
            {venue.verifiedBy.cred.map(c => (
              <span key={c} style={{ background: 'rgba(255,255,255,0.1)', padding: '4px 10px', borderRadius: 999, fontSize: 11 }}>{c}</span>
            ))}
          </div>
          <div style={{ marginTop: 10, fontSize: 11.5, color: 'rgba(255,255,255,0.7)' }}>
            Visited <strong style={{ color: 'var(--accent)' }}>{venue.verifiedBy.visits}×</strong> by Wayfare scouts
          </div>
        </div>

        <button className="btn btn--accent" style={{ width: '100%', justifyContent: 'center', marginTop: 18 }}>
          Add to itinerary <Icon.arrow />
        </button>
      </div>
    </div>
  );
}

/* ----------- Screen: Camera AI ----------- */
function ScreenCamera({ onBack }) {
  const [stage, setStage] = useState('intro'); // intro | scanning | result
  const fileRef = useRef(null);

  const trigger = () => {
    setStage('scanning');
    setTimeout(() => setStage('result'), 2400);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppHeader title="Camera AI guide" onBack={onBack} />
      <div style={{ padding: 16, flex: 1, overflow: 'auto' }}>
        {stage === 'intro' && (
          <>
            <p style={{ fontSize: 13.5, color: 'var(--muted)', marginTop: 0 }}>Point your camera at a venue, doorway or menu. Wayfare AI will describe what it sees, focused on accessibility.</p>
            <div style={{
              aspectRatio: '4/5',
              background: 'linear-gradient(140deg, #1F4D3F, #2C5A48)',
              borderRadius: 16,
              display: 'grid', placeItems: 'center',
              color: '#fff',
              border: '1.5px solid var(--ink)',
              position: 'relative',
              overflow: 'hidden',
            }}>
              {/* corner brackets */}
              {[[10, 10, 0], [10, 10, 90], [10, 10, 180], [10, 10, 270]].map((_, i) => (
                <span key={i} style={{
                  position: 'absolute',
                  width: 28, height: 28,
                  borderTop: '2.5px solid #fff',
                  borderLeft: '2.5px solid #fff',
                  top: i < 2 ? 14 : 'auto',
                  bottom: i >= 2 ? 14 : 'auto',
                  left: i % 2 === 0 ? 14 : 'auto',
                  right: i % 2 === 1 ? 14 : 'auto',
                  transform: i === 1 ? 'rotate(90deg)' : i === 2 ? 'rotate(-90deg)' : i === 3 ? 'rotate(180deg)' : 'none',
                }} />
              ))}
              <div style={{ textAlign: 'center' }}>
                <Icon.camera width="48" height="48" />
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18, marginTop: 12 }}>Show me what you see</div>
                <div style={{ fontSize: 12, opacity: 0.7, marginTop: 4 }}>or upload from photos</div>
              </div>
            </div>
            <button onClick={trigger} className="btn btn--accent" style={{ width: '100%', justifyContent: 'center', marginTop: 14 }}>
              <Icon.camera width="16" height="16" /> Capture / upload
            </button>
            <button onClick={trigger} className="btn btn--ghost btn--sm" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>
              Use sample image
            </button>
          </>
        )}

        {stage === 'scanning' && (
          <div style={{ display: 'grid', placeItems: 'center', height: '100%', textAlign: 'center', padding: 30 }}>
            <div>
              <div style={{ width: 84, height: 84, borderRadius: 999, background: 'var(--primary-soft)', display: 'grid', placeItems: 'center', margin: '0 auto', position: 'relative' }}>
                <Icon.camera width="32" height="32" />
                <span style={{ position: 'absolute', inset: 0, borderRadius: 999, border: '2px solid var(--primary)', animation: 'pulseRing 1.4s infinite' }} />
              </div>
              <p style={{ fontFamily: 'var(--font-serif)', fontSize: 18, margin: '16px 0 4px' }}>Looking at your photo</p>
              <p style={{ fontSize: 12, color: 'var(--muted)' }}>Wayfare AI on Wayfare AI · multimodal</p>
            </div>
          </div>
        )}

        {stage === 'result' && (
          <div>
            <VenuePhoto kind="cafe" accent="#7BAA80" height={140} label="Your photo" />
            <div style={{ marginTop: 14, padding: 14, background: 'var(--surface)', border: '1.5px solid var(--line)', borderRadius: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--primary)', fontWeight: 700, textTransform: 'uppercase' }}>● Wayfare vision</span>
                <button aria-label="Read aloud" style={{ marginLeft: 'auto', background: 'transparent', border: 0 }}>
                  <Icon.volume width="14" height="14" />
                </button>
              </div>
              <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.5 }}>
                I can see <strong>a café entrance with two stone steps</strong>, roughly 12 cm each. There <em>is</em> a side ramp on the right at gentle gradient — about 1:14. The doorway looks 90 cm wide. The entry mat is flush, no lip. A handrail runs along the ramp on one side.
              </p>
              <div style={{ marginTop: 12, padding: 10, background: 'var(--bg-alt)', borderRadius: 10, fontSize: 12.5, lineHeight: 1.45 }}>
                <strong style={{ display: 'block', marginBottom: 4 }}>Likely accessible if:</strong>
                You can use the side ramp — front entrance has steps.
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
                <button className="chip">Ask: width of door?</button>
                <button className="chip">Ask: indoor seating?</button>
                <button className="chip">Translate sign</button>
              </div>
            </div>
            <button onClick={() => setStage('intro')} className="btn btn--ghost btn--sm" style={{ width: '100%', justifyContent: 'center', marginTop: 12 }}>
              Take another photo
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ----------- App preview shell ----------- */
function AppPreview({ initialScreen = 'plan' }) {
  const [screen, setScreen] = useState(initialScreen);
  const [needs, setNeeds] = useState(['wheelchair', 'quiet']);
  const [query, setQuery] = useState('');
  const [listening, setListening] = useState(false);
  const [activeVenue, setActiveVenue] = useState(VENUE_DATA[0]);
  const [emergencyOpen, setEmergencyOpen] = useState(false);

  return (
    <div className="phone" role="region" aria-label="Wayfare app preview">
      <div className="phone__notch" />
      <div className="phone__screen">
        {/* Status bar */}
        <div style={{
          height: 38,
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
          padding: '0 22px 6px',
          fontSize: 12.5, fontWeight: 700,
          fontFamily: 'var(--font-mono)',
          color: 'var(--ink)',
          background: 'var(--surface)',
        }}>
          <span>9:41</span>
          <span style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
            <span style={{ fontSize: 11 }}>5G</span>
            <span style={{ display: 'inline-block', width: 22, height: 11, border: '1.5px solid var(--ink)', borderRadius: 3, position: 'relative' }}>
              <span style={{ position: 'absolute', inset: 1, background: 'var(--ink)', width: '70%' }} />
            </span>
          </span>
        </div>

        {/* Screen */}
        <div style={{ height: 'calc(100% - 38px)', overflow: 'hidden', position: 'relative' }}>
          {screen === 'plan' && (
            <ScreenPlan
              needs={needs} setNeeds={setNeeds}
              query={query} setQuery={setQuery}
              listening={listening} setListening={setListening}
              onSubmit={() => setScreen('results')}
            />
          )}
          {screen === 'results' && (
            <ScreenResults
              needs={needs}
              query={query}
              onBack={() => setScreen('plan')}
              onOpen={(v) => { setActiveVenue(v); setScreen('detail'); }}
              onCamera={() => setScreen('camera')}
            />
          )}
          {screen === 'detail' && (
            <ScreenDetail venue={activeVenue} onBack={() => setScreen('results')} />
          )}
          {screen === 'camera' && (
            <ScreenCamera onBack={() => setScreen('results')} />
          )}

          {/* in-app emergency */}
          <button
            onClick={() => setEmergencyOpen(true)}
            aria-label="Emergency"
            style={{
              position: 'absolute', bottom: 14, right: 14, zIndex: 5,
              background: 'var(--emergency)', color: '#fff', border: '2px solid #fff',
              width: 44, height: 44, borderRadius: 999,
              display: 'grid', placeItems: 'center',
              fontWeight: 800,
              boxShadow: '0 10px 24px -6px rgba(196,48,43,0.5)',
              animation: 'pulseRing 1.8s infinite',
            }}
          >!</button>
        </div>
      </div>

      {/* Screen switcher (outside the phone) */}
      <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 16, flexWrap: 'wrap' }}>
        {[
          { k: 'plan', label: 'Plan' },
          { k: 'results', label: 'Results' },
          { k: 'detail', label: 'Detail' },
          { k: 'camera', label: 'Camera AI' },
        ].map(s => (
          <button
            key={s.k}
            onClick={() => setScreen(s.k)}
            className="chip"
            aria-pressed={screen === s.k}
            style={{ background: screen === s.k ? 'var(--bg)' : 'transparent', borderColor: 'var(--bg)', color: screen === s.k ? 'var(--ink)' : 'var(--bg)' }}
          >{s.label}</button>
        ))}
      </div>

      <EmergencyModal open={emergencyOpen} onClose={() => setEmergencyOpen(false)} />
    </div>
  );
}

Object.assign(window, { AppPreview, VenuePhoto, VENUE_DATA, NEED_OPTIONS });
