/* ============================================================
   Wayfare — shared components
   - Brand mark / Nav / Emergency FAB / A11y toolbar
   - Lighthouse score visualization
   - Voice input control
   - Icons (inline SVG)
   ============================================================ */

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

/* ----------- Icons ----------- */
const Icon = {
  mic: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" width="20" height="20" {...p}>
      <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
      <path d="M5 11a7 7 0 0 0 14 0" />
      <path d="M12 18v3" />
    </svg>
  ),
  arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M5 12h14" /><path d="m13 5 7 7-7 7" />
    </svg>
  ),
  arrowUp: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="16" height="16" {...p}>
      <path d="M7 17 17 7" /><path d="M8 7h9v9" />
    </svg>
  ),
  check: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" width="14" height="14" {...p}>
      <path d="m5 12 5 5L20 7" />
    </svg>
  ),
  camera: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="20" height="20" {...p}>
      <path d="M3 8a2 2 0 0 1 2-2h2.5l1.5-2h6l1.5 2H19a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z" />
      <circle cx="12" cy="13" r="4" />
    </svg>
  ),
  pin: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="16" height="16" {...p}>
      <path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" /><circle cx="12" cy="10" r="3" />
    </svg>
  ),
  shield: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M12 2 4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6Z" /><path d="m9 12 2 2 4-4" />
    </svg>
  ),
  star: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16" {...p}>
      <path d="M12 2 14.6 9 22 9.5l-5.6 4.7L18.2 22 12 17.8 5.8 22l1.8-7.8L2 9.5 9.4 9Z" />
    </svg>
  ),
  sparkle: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8" />
    </svg>
  ),
  bedrock: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M12 3 4 8v8l8 5 8-5V8Z" /><path d="M4 8l8 5 8-5" /><path d="M12 13v8" />
    </svg>
  ),
  wheelchair: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <circle cx="11" cy="5" r="2" />
      <path d="M11 7v6h5l3 6" />
      <circle cx="11" cy="17" r="5" />
    </svg>
  ),
  eye: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" /><circle cx="12" cy="12" r="3" />
    </svg>
  ),
  ear: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M6 8a6 6 0 1 1 12 0c0 3-2 4-3.5 5.5S13 16 13 18a3 3 0 0 1-6 0" />
    </svg>
  ),
  brain: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-2 5 3 3 0 0 0 2 5v1a3 3 0 0 0 6 0V4" />
      <path d="M15 4a3 3 0 0 1 3 3v1a3 3 0 0 1 2 5 3 3 0 0 1-2 5v1a3 3 0 0 1-6 0" />
    </svg>
  ),
  utensils: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M4 3v6a2 2 0 0 0 2 2v10" /><path d="M8 3v8" /><path d="M16 21V3c-2 0-3 2-3 5s1 5 3 5v8Z" />
    </svg>
  ),
  volume: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" width="18" height="18" {...p}>
      <path d="M11 5 6 9H3v6h3l5 4Z" /><line x1="22" x2="16" y1="9" y2="15" /><line x1="16" x2="22" y1="9" y2="15" />
    </svg>
  ),
  plus: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" width="14" height="14" {...p}>
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
};

/* ----------- Brand mark ----------- */
function Brandmark({ size = 30 }) {
  return (
    <span className="nav__brand-mark" style={{ width: size, height: size, fontSize: size * 0.62 }} aria-hidden="true">W</span>
  );
}

/* ----------- A11y toolbar ----------- */
function A11yToolbar({ fontScale, setFontScale, reduceMotion, setReduceMotion, theme, setTheme }) {
  return (
    <div className="a11y-bar" role="toolbar" aria-label="Accessibility preferences">
      <button
        aria-label="Decrease text size"
        onClick={() => setFontScale(Math.max(0.85, +(fontScale - 0.1).toFixed(2)))}
        title="Smaller text"
      >
        <span style={{ fontSize: 11 }}>A</span>
      </button>
      <button
        aria-label="Increase text size"
        onClick={() => setFontScale(Math.min(1.4, +(fontScale + 0.1).toFixed(2)))}
        title="Larger text"
      >
        <span style={{ fontSize: 16 }}>A</span>
      </button>
      <span style={{ width: 1, height: 16, background: 'var(--line)' }} />
      <button
        aria-pressed={theme === 'contrast'}
        onClick={() => setTheme(theme === 'contrast' ? 'soft' : 'contrast')}
        title="High-contrast mode"
      >
        ◐ Contrast
      </button>
      <button
        aria-pressed={reduceMotion}
        onClick={() => setReduceMotion(!reduceMotion)}
        title="Reduce motion"
      >
        Motion {reduceMotion ? 'off' : 'on'}
      </button>
    </div>
  );
}

/* ----------- Nav ----------- */
function Nav({ a11yProps, onEmergency }) {
  const [open, setOpen] = useState(false);
  return (
    <nav className="nav" aria-label="Primary">
      <div className="wrap nav__inner">
        <a href="#top" className="nav__brand" aria-label="Wayfare home">
          <Brandmark />
          <span>Wayfare</span>
        </a>
        <ul className="nav__links">
          <li><a href="#problem">The problem</a></li>
          <li><a href="#how">How it works</a></li>
          <li><a href="#score">Wayfare Score</a></li>
          <li><a href="#scouts">Scouts</a></li>
          <li><a href="#app">The app</a></li>
          <li><a href="#faq">FAQ</a></li>
        </ul>
        <div className="nav__cta">
          <A11yToolbar {...a11yProps} />
          <a href="Sign In.html" className="btn btn--sm btn--ghost" style={{ display: 'inline-flex' }}>
            Sign in
          </a>
          <a href="Sign Up.html" className="btn btn--sm" style={{ display: 'inline-flex' }}>
            Get started <Icon.arrow />
          </a>
        </div>
      </div>
    </nav>
  );
}

/* ----------- Emergency button (persistent) ----------- */
function EmergencyFAB({ onClick }) {
  return (
    <button className="emergency-fab" onClick={onClick} aria-label="Open emergency safety panel">
      <span className="emergency-fab__dot" aria-hidden="true">!</span>
      <span>Emergency</span>
    </button>
  );
}

/* ----------- Camera AI button (persistent, mirrors Emergency) ----------- */
function CameraFAB({ onClick }) {
  return (
    <button className="camera-fab" onClick={onClick} aria-label="Open Camera AI guide">
      <span className="camera-fab__dot" aria-hidden="true">
        <Icon.camera width="16" height="16" />
      </span>
      <span>Camera AI</span>
    </button>
  );
}

/* ----------- Emergency modal ----------- */
function EmergencyModal({ open, onClose }) {
  const [stage, setStage] = useState('idle'); // idle | confirming | sharing | done
  useEffect(() => { if (open) setStage('idle'); }, [open]);

  useEffect(() => {
    if (stage === 'confirming') {
      const t = setTimeout(() => setStage('sharing'), 1400);
      return () => clearTimeout(t);
    }
    if (stage === 'sharing') {
      const t = setTimeout(() => setStage('done'), 2200);
      return () => clearTimeout(t);
    }
  }, [stage]);

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="em-title"
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(15, 25, 20, 0.45)',
        display: 'grid', placeItems: 'center',
        padding: 20,
      }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div style={{
        width: '100%', maxWidth: 460,
        background: 'var(--surface)', borderRadius: 22,
        border: '2px solid var(--emergency)',
        overflow: 'hidden',
        boxShadow: '0 30px 60px -20px rgba(0,0,0,0.4)',
      }}>
        <div style={{ background: 'var(--emergency)', color: '#fff', padding: '18px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 28, height: 28, borderRadius: 999, background: '#fff', color: 'var(--emergency)', display: 'grid', placeItems: 'center', fontWeight: 800 }}>!</span>
            <strong id="em-title" style={{ fontFamily: 'var(--font-serif)', fontWeight: 500, fontSize: 20 }}>Emergency assistance</strong>
          </div>
          <button onClick={onClose} aria-label="Close emergency panel" style={{ background: 'transparent', border: 0, color: '#fff', fontSize: 22, lineHeight: 1 }}>×</button>
        </div>

        <div style={{ padding: 24 }}>
          {stage === 'idle' && (
            <>
              <p style={{ marginTop: 0, fontSize: 15.5, color: 'var(--ink-soft)' }}>
                In a real emergency, Wayfare will share your live location, accessibility profile and emergency contacts with local services.
              </p>
              <div style={{ background: 'var(--bg-alt)', borderRadius: 12, padding: 14, marginBottom: 18, fontSize: 14, display: 'grid', gap: 6 }}>
                <div><strong>Calling:</strong> 112 — Indian Emergency Response</div>
                <div><strong>Sharing with:</strong> Mum (+91 98••• 22), Priya (+91 87••• 04)</div>
                <div><strong>Profile:</strong> Wheelchair user · Type-1 diabetic · O+ blood</div>
              </div>
              <p style={{ margin: 0, fontSize: 13, color: 'var(--muted)' }}>This is a live product — no real call will be placed.</p>
              <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
                <button className="btn btn--ghost" onClick={onClose} style={{ flex: 1 }}>Cancel</button>
                <button className="btn" onClick={() => setStage('confirming')} style={{ flex: 1.4, background: 'var(--emergency)' }}>
                  Confirm call
                </button>
              </div>
            </>
          )}
          {stage === 'confirming' && (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div className="wave" style={{ height: 38, justifyContent: 'center' }}>
                <span /><span /><span /><span /><span /><span />
              </div>
              <p style={{ marginTop: 16, fontFamily: 'var(--font-serif)', fontSize: 22 }}>Connecting to 112…</p>
            </div>
          )}
          {stage === 'sharing' && (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <p style={{ fontFamily: 'var(--font-serif)', fontSize: 22, marginTop: 0 }}>Sharing your details</p>
              <div style={{ display: 'grid', gap: 8, textAlign: 'left', fontSize: 14 }}>
                <Step label="📍 Live location shared with dispatch" />
                <Step label="🪪 Accessibility profile attached" />
                <Step label="📨 SMS sent to 2 emergency contacts" />
              </div>
            </div>
          )}
          {stage === 'done' && (
            <div style={{ textAlign: 'center', padding: '12px 0' }}>
              <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--success)', color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}>
                <Icon.check width="28" height="28" />
              </div>
              <p style={{ fontFamily: 'var(--font-serif)', fontSize: 22, marginTop: 0 }}>Help is on the way</p>
              <p style={{ color: 'var(--muted)', fontSize: 14, margin: 0 }}>Estimated arrival 6 min. Stay on this screen.</p>
              <button className="btn btn--ghost" onClick={onClose} style={{ marginTop: 18 }}>Dismiss</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
function Step({ label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: 'var(--bg-alt)', borderRadius: 10 }}>
      <span style={{ width: 18, height: 18, borderRadius: 999, background: 'var(--success)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 11 }}><Icon.check width="10" height="10" /></span>
      <span>{label}</span>
    </div>
  );
}

/* ----------- Voice Input ----------- */
function VoiceInput({ value, onChange, onSubmit, placeholder = "I'm a wheelchair user planning a trip to Jaipur in March…", presets = [] }) {
  const [listening, setListening] = useState(false);
  const [typed, setTyped] = useState('');
  const phrases = [
    "I'm a wheelchair user going to Jaipur in March, need step-free hotels and quiet restaurants…",
    "Travelling with my mum who has low vision. Bangalore, 4 days, prefers calm museums…",
    "Type 1 diabetic, halal food, planning a 3-day Goa trip with my partner…",
  ];

  // Simulate transcription on listening
  useEffect(() => {
    if (!listening) return;
    const phrase = phrases[Math.floor(Math.random() * phrases.length)];
    let i = 0;
    setTyped('');
    const id = setInterval(() => {
      i += Math.max(1, Math.round(phrase.length / 60));
      setTyped(phrase.slice(0, i));
      if (i >= phrase.length) {
        clearInterval(id);
        onChange(phrase);
        setListening(false);
      }
    }, 60);
    return () => clearInterval(id);
  }, [listening]);

  return (
    <div style={{
      background: 'var(--surface)',
      border: '1.5px solid var(--ink)',
      borderRadius: 22,
      padding: 14,
      boxShadow: 'var(--shadow-2)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 6px 10px' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', color: 'var(--primary)', fontWeight: 700, textTransform: 'uppercase' }}>● WAYFARE AI</span>
        <span style={{ flex: 1 }} />
        <span style={{ fontSize: 12, color: 'var(--muted)' }}>Voice or text</span>
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <button
          aria-label={listening ? 'Stop listening' : 'Start voice input'}
          onClick={() => setListening((l) => !l)}
          style={{
            flexShrink: 0,
            width: 52, height: 52,
            borderRadius: 999,
            border: '1.5px solid ' + (listening ? 'var(--emergency)' : 'var(--ink)'),
            background: listening ? 'var(--emergency)' : 'var(--ink)',
            color: '#fff',
            display: 'grid', placeItems: 'center',
            animation: listening ? 'pulseRing 1.4s infinite' : 'none',
          }}
        >
          <Icon.mic width="22" height="22" />
        </button>
        <textarea
          value={listening ? typed : value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          rows={2}
          aria-label="Describe your trip needs"
          style={{
            flex: 1,
            border: 0,
            background: 'transparent',
            font: 'inherit',
            fontSize: 16.5,
            color: 'var(--ink)',
            resize: 'none',
            outline: 'none',
            paddingTop: 6,
            lineHeight: 1.4,
          }}
        />
        <button
          className="btn btn--accent"
          onClick={onSubmit}
          aria-label="Plan my itinerary"
          style={{ flexShrink: 0, alignSelf: 'flex-end' }}
        >
          Plan trip <Icon.arrow />
        </button>
      </div>
      {listening && (
        <div style={{ paddingTop: 12, display: 'flex', alignItems: 'center', gap: 12 }}>
          <span className="wave"><span /><span /><span /><span /><span /><span /></span>
          <span style={{ fontSize: 13, color: 'var(--muted)' }}>Listening · Voice input</span>
        </div>
      )}
      {presets.length > 0 && !listening && (
        <div style={{ paddingTop: 12, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {presets.map((p) => (
            <button key={p} className="chip" onClick={() => onChange(p)}>{p}</button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ----------- Lighthouse Score Visualization ----------- */
function LighthouseScore({ score = 92, size = 120, label = "Wayfare Score" }) {
  const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : score >= 60 ? 'D' : 'F';
  const color =
    grade === 'A' ? 'var(--score-A)' :
    grade === 'B' ? 'var(--score-B)' :
    grade === 'C' ? 'var(--score-C)' :
    grade === 'D' ? 'var(--score-D)' : 'var(--score-F)';

  const r = 48;
  const circumference = 2 * Math.PI * r;
  const offset = circumference - (score / 100) * circumference;

  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 14 }}>
      <svg width={size} height={size} viewBox="0 0 120 120" aria-label={`${label}: ${score} out of 100, grade ${grade}`}>
        <circle cx="60" cy="60" r={r} fill="none" stroke="var(--line)" strokeWidth="8" />
        <circle
          cx="60" cy="60" r={r}
          fill="none"
          stroke={color}
          strokeWidth="8"
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          transform="rotate(-90 60 60)"
          style={{ transition: 'stroke-dashoffset 1s var(--easing)' }}
        />
        <text x="60" y="58" textAnchor="middle" fontFamily="var(--font-serif)" fontSize="34" fontWeight="500" fill="var(--ink)">{score}</text>
        <text x="60" y="80" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="2" fill={color} fontWeight="700">GRADE {grade}</text>
      </svg>
      {label && (
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 600 }}>{label}</div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, marginTop: 4 }}>{score >= 85 ? 'Excellent' : score >= 70 ? 'Good' : score >= 55 ? 'Fair' : 'Limited'}</div>
        </div>
      )}
    </div>
  );
}

/* ----------- Mini score pill (for cards) ----------- */
function ScorePill({ score }) {
  const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : score >= 60 ? 'D' : 'F';
  return (
    <span className={`score score__grade-${grade}`}>
      <span className="score__num">{score}</span>
      <span style={{ paddingRight: 6 }}>Wayfare · {grade}</span>
    </span>
  );
}

/* ----------- Need-type icons ----------- */
const NEED_ICONS = {
  wheelchair: { icon: Icon.wheelchair, label: 'Mobility' },
  vision: { icon: Icon.eye, label: 'Vision' },
  hearing: { icon: Icon.ear, label: 'Hearing' },
  cognitive: { icon: Icon.brain, label: 'Cognitive' },
  dietary: { icon: Icon.utensils, label: 'Dietary' },
  quiet: { icon: Icon.volume, label: 'Quiet' },
};

/* ----------- Scout avatar (photo with initial fallback) ----------- */
function ScoutAvatar({ name, photo, color = 'var(--primary)', size = 40, ring }) {
  const [err, setErr] = useState(false);
  const initial = (name?.split(' ').map(p => p[0]).slice(0, 2).join('') || '?').toUpperCase();
  const showImg = photo && !err;
  return (
    <span
      style={{
        width: size, height: size, flexShrink: 0,
        borderRadius: 999,
        background: color,
        color: '#fff',
        display: 'grid', placeItems: 'center',
        fontFamily: 'var(--font-serif)',
        fontWeight: 500,
        fontSize: size * 0.42,
        overflow: 'hidden',
        position: 'relative',
        boxShadow: ring ? `0 0 0 2px ${ring}` : 'none',
      }}
      aria-hidden="true"
    >
      {showImg ? (
        <img
          src={photo}
          alt=""
          loading="lazy"
          onError={() => setErr(true)}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
        />
      ) : (
        <span>{initial}</span>
      )}
    </span>
  );
}

/* ----------- Export to global scope ----------- */
Object.assign(window, {
  Icon, Brandmark, A11yToolbar, Nav,
  EmergencyFAB, EmergencyModal, CameraFAB,
  VoiceInput, LighthouseScore, ScorePill, NEED_ICONS,
  ScoutAvatar,
});
