// Shared components for Pacific Search AI site

const NAVY = '#0B1E3F', CREAM = '#F4EFE6', CITRUS = '#D9FF4F', SURF = '#7DBBC2', FOG = '#EDEDED', GRAPH = '#2B2B2B';

// ─── Logo (bracket wordmark) ───────────────────────────
function Logo({ size = 22, fg = NAVY }) {
  const bracket = Math.round(size * 0.85);
  const tag = Math.round(size * 0.48);
  return (
    <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: size * 0.18, fontFamily: 'Fraunces, serif', fontWeight: 300, fontSize: size, color: fg, letterSpacing: '-0.02em', lineHeight: 1 }}>
      <span style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 400, fontSize: bracket, opacity: 0.6 }}>[</span>
      <span>Pacific Search</span>
      <span style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 400, fontSize: bracket, opacity: 0.6 }}>]</span>
      <span style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 500, fontSize: tag, background: CITRUS, color: NAVY, padding: `${size*0.08}px ${size*0.17}px`, marginLeft: size*0.1, alignSelf: 'center' }}>.ai</span>
    </span>
  );
}

// ─── Nav ──────────────────────────────────────────────
function Nav({ current }) {
  const links = [
    { href: 'index.html', label: 'Home', key: 'home' },
    { href: 'how-it-works.html', label: 'How it works', key: 'how' },
    { href: 'pricing.html', label: 'Pricing', key: 'pricing' },
    { href: 'about.html', label: 'About', key: 'about' },
  ];
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a href="index.html" style={{ display: 'flex', alignItems: 'center' }}>
          <Logo size={20} />
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.key} href={l.href} className={current === l.key ? 'active' : ''}>{l.label}</a>
          ))}
          <a href="contact.html" className="btn btn-cta" style={{ padding: '10px 18px' }}>
            Free AI audit <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </nav>
  );
}

// ─── Footer ───────────────────────────────────────────
function Footer() {
  return (
    <footer>
      <div className="wrap">
        <div className="foot-grid">
          <div>
            <Logo size={20} fg={CREAM} />
            <p style={{ color: CREAM, opacity: 0.7, marginTop: 18, fontSize: 14, maxWidth: 320 }}>
              AI search visibility for med spas, dentists, and local businesses. Built in San Diego.
            </p>
          </div>
          <div className="foot-col">
            <h4>Site</h4>
            <a href="index.html">Home</a>
            <a href="how-it-works.html">How it works</a>
            <a href="pricing.html">Pricing</a>
            <a href="about.html">About</a>
          </div>
          <div className="foot-col">
            <h4>Start</h4>
            <a href="contact.html">Free AI audit</a>
            <a href="https://cal.com/pacificsearch/15min">Book a call</a>
            <a href="mailto:hello@pacificsearchai.com">hello@pacificsearchai.com</a>
          </div>
          <div className="foot-col">
            <h4>Location</h4>
            <a>San Diego, CA</a>
            <a>32.7° N · 117.1° W</a>
          </div>
        </div>
        <div className="foot-meta">
          <span>© 2026 Pacific Search AI</span>
          <span>Privacy · Terms</span>
        </div>
      </div>
    </footer>
  );
}

// ─── Hero art: CSS-only horizon + sun ─────────────────
function HeroArt({ variant = 'horizon' }) {
  if (variant === 'bars') {
    return (
      <div className="hero-art-wrap" style={{ position: 'relative', height: '100%', minHeight: 480, overflow: 'hidden' }}>
        {[0, 1, 2, 3, 4].map(i => (
          <div key={i} style={{
            position: 'absolute', left: 0, right: 0,
            top: `${20 + i * 14}%`,
            height: 1, background: NAVY, opacity: 0.15 + i * 0.12,
          }} />
        ))}
        <div style={{
          position: 'absolute', right: '12%', top: '38%',
          width: 180, height: 180, borderRadius: '50%',
          background: CITRUS, mixBlendMode: 'multiply',
          boxShadow: `0 0 0 1px ${NAVY}`,
        }} />
      </div>
    );
  }
  if (variant === 'compass') {
    return (
      <div className="hero-art-wrap" style={{ position: 'relative', height: '100%', minHeight: 480, display: 'grid', placeItems: 'center' }}>
        <svg viewBox="0 0 400 400" width="70%" style={{ maxWidth: 460 }}>
          <circle cx="200" cy="200" r="180" fill="none" stroke={NAVY} strokeWidth="1" />
          <circle cx="200" cy="200" r="140" fill="none" stroke={NAVY} strokeWidth="0.5" />
          <line x1="200" y1="20" x2="200" y2="380" stroke={NAVY} strokeWidth="0.5" />
          <line x1="20" y1="200" x2="380" y2="200" stroke={NAVY} strokeWidth="0.5" />
          <path d="M20 200 L 120 188 L 120 212 Z" fill={CITRUS} stroke={NAVY} strokeWidth="1" />
          <circle cx="200" cy="200" r="6" fill={NAVY} />
        </svg>
      </div>
    );
  }
  // horizon (default)
  return (
    <div className="hero-art-wrap" style={{ position: 'relative', height: '100%', minHeight: 480, overflow: 'hidden' }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(180deg, ${CREAM} 0%, ${CREAM} 55%, color-mix(in srgb, ${SURF} 40%, ${CREAM}) 100%)`,
      }} />
      <div style={{
        position: 'absolute', left: '8%', right: '8%', top: '55%',
        height: 1, background: NAVY, opacity: 0.6,
      }} />
      <div style={{
        position: 'absolute', left: '8%', right: '8%', top: '58%',
        height: 1, background: NAVY, opacity: 0.15,
      }} />
      <div style={{
        position: 'absolute', left: '50%', top: '44%',
        width: 110, height: 110, borderRadius: '50%',
        background: CITRUS, transform: 'translateX(-50%)',
        boxShadow: `0 0 0 1px ${NAVY}`,
        animation: 'sunrise 8s ease-in-out infinite alternate',
      }} />
      <style>{`@keyframes sunrise { 0% { transform: translateX(-50%) translateY(8px); } 100% { transform: translateX(-50%) translateY(-4px); } }`}</style>
      <div style={{
        position: 'absolute', bottom: 24, left: '8%',
        fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
        letterSpacing: '0.25em', color: NAVY, opacity: 0.5, textTransform: 'uppercase',
      }}>32.7°N · Pacific · 06:12</div>
    </div>
  );
}

// ─── Score dial (animates on scroll into view) ────────
function ScoreDial({ from = 12, to = 67, label = 'AI Visibility Score', delay = 0 }) {
  const [val, setVal] = React.useState(from);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setTimeout(() => {
          const start = performance.now();
          const dur = 1400;
          const tick = (t) => {
            const p = Math.min(1, (t - start) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(Math.round(from + (to - from) * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }, delay);
        obs.disconnect();
      }
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [from, to, delay]);
  const pct = val / 100;
  const R = 70, C = 2 * Math.PI * R;
  return (
    <div ref={ref} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
      <div style={{ position: 'relative', width: 180, height: 180 }}>
        <svg width="180" height="180" viewBox="0 0 180 180" style={{ transform: 'rotate(-90deg)' }}>
          <circle cx="90" cy="90" r={R} fill="none" stroke={FOG} strokeWidth="6" />
          <circle cx="90" cy="90" r={R} fill="none" stroke={CITRUS} strokeWidth="6"
                  strokeDasharray={C} strokeDashoffset={C * (1 - pct)}
                  strokeLinecap="butt" style={{ transition: 'stroke-dashoffset .1s linear' }} />
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: 'Fraunces, serif', fontWeight: 300, fontSize: 56, color: NAVY, lineHeight: 1 }}>
              {val}
            </div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.15em', color: NAVY, opacity: 0.5, marginTop: 4 }}>
              / 100
            </div>
          </div>
        </div>
      </div>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.2em', color: NAVY, opacity: 0.6, textTransform: 'uppercase' }}>{label}</div>
    </div>
  );
}

// ─── Audit input ─────────────────────────────────────
function AuditInput() {
  const [url, setUrl] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [state, setState] = React.useState('idle'); // idle | error | sent
  const submit = (e) => {
    e.preventDefault();
    try {
      const u = url.trim();
      if (!/^https?:\/\//i.test(u) && !/\./.test(u)) { setState('error'); return; }
      if (!/\S+@\S+\.\S+/.test(email)) { setState('error'); return; }
      setState('sent');
    } catch { setState('error'); }
  };
  if (state === 'sent') {
    return (
      <div className="card" style={{ background: CITRUS, border: `1px solid ${NAVY}` }}>
        <div style={{ fontFamily: 'Fraunces, serif', fontWeight: 500, fontSize: 22, color: NAVY, letterSpacing: '-0.02em' }}>
          Got it. We'll email you results within 24 hours.
        </div>
        <div style={{ marginTop: 8, fontSize: 13, color: NAVY, opacity: 0.8 }}>
          We run 25 queries across 5 AI engines. You'll get a PDF + a 15-min walkthrough offer.
        </div>
      </div>
    );
  }
  return (
    <form onSubmit={submit} className="card" style={{ background: '#fff' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 16 }}>
        <div>
          <label>Your website</label>
          <input type="text" placeholder="yourbusiness.com" value={url} onChange={e => { setUrl(e.target.value); setState('idle'); }} />
        </div>
        <div>
          <label>Email</label>
          <input type="email" placeholder="you@business.com" value={email} onChange={e => { setEmail(e.target.value); setState('idle'); }} />
        </div>
      </div>
      {state === 'error' && <div style={{ fontSize: 12, color: '#c0392b', fontFamily: 'JetBrains Mono, monospace', marginTop: 12 }}>Check your URL and email.</div>}
      <div style={{ marginTop: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.15em', color: NAVY, opacity: 0.55, textTransform: 'uppercase' }}>
          25 queries · 5 engines · 24h turnaround · free
        </div>
        <button type="submit" className="btn btn-cta">Run my audit <span className="arrow">→</span></button>
      </div>
    </form>
  );
}

// ─── FAQ accordion ───────────────────────────────────
function FAQ({ items }) {
  const [open, setOpen] = React.useState(0);
  return (
    <div>
      {items.map((it, i) => (
        <div key={i} style={{ borderTop: `1px solid ${FOG}`, padding: '24px 0' }}>
          <button
            onClick={() => setOpen(open === i ? -1 : i)}
            style={{ width: '100%', background: 'none', border: 'none', textAlign: 'left', padding: 0, cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
            <div style={{ fontFamily: 'Fraunces, serif', fontWeight: 500, fontSize: 22, color: NAVY, letterSpacing: '-0.015em' }}>
              {it.q}
            </div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 20, color: NAVY, opacity: 0.6, transform: open === i ? 'rotate(45deg)' : 'none', transition: 'transform .2s' }}>+</div>
          </button>
          {open === i && (
            <div style={{ marginTop: 14, fontSize: 15, color: GRAPH, maxWidth: '70ch', lineHeight: 1.65 }}>{it.a}</div>
          )}
        </div>
      ))}
      <div style={{ borderTop: `1px solid ${FOG}` }} />
    </div>
  );
}

// ─── Pricing toggle + cards ──────────────────────────
const PRICING_TIERS = [
  { name: 'Starter', monthly: 1500, blurb: 'Local visibility for single-location clinics.', bullets: ['25 queries / 5 engines monthly', 'Weekly citation tracking', '2 content briefs / mo', 'Quarterly strategy call', 'Email support'] },
  { name: 'Growth', monthly: 2750, blurb: 'For clinics ready to dominate their city.', featured: true, bullets: ['50 queries / 5 engines weekly', 'Daily citation tracking', '4 content pieces / mo', 'Monthly strategy call', 'Schema + review ops', 'Email support'] },
  { name: 'Scale', monthly: 4500, blurb: 'Multi-location or competitive markets.', bullets: ['100 queries / 5 engines weekly', 'Real-time citation monitoring', '8 content pieces / mo', 'Bi-weekly strategy call', 'Full-funnel optimization', 'Dedicated email and Slack'] },
];

function PricingCards() {
  const [annual, setAnnual] = React.useState(false);
  const save = 0.15; // 15% off annual
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 40 }}>
        <div style={{ display: 'inline-flex', background: '#fff', border: `1px solid ${FOG}`, borderRadius: 999, padding: 4 }}>
          {[['Monthly', false], ['Annual — save 15%', true]].map(([l, v]) => (
            <button key={String(v)} onClick={() => setAnnual(v)} style={{
              padding: '10px 22px', borderRadius: 999, border: 'none', cursor: 'pointer',
              background: annual === v ? NAVY : 'transparent',
              color: annual === v ? CREAM : NAVY,
              fontFamily: 'Inter, sans-serif', fontWeight: 500, fontSize: 13,
              transition: 'background .15s',
            }}>{l}</button>
          ))}
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
        {PRICING_TIERS.map(t => {
          const price = annual ? Math.round(t.monthly * (1 - save)) : t.monthly;
          return (
            <div key={t.name} className="card" style={{
              position: 'relative',
              background: t.featured ? NAVY : '#fff',
              color: t.featured ? CREAM : GRAPH,
              border: t.featured ? `1px solid ${NAVY}` : `1px solid ${FOG}`,
              padding: 36,
            }}>
              {t.featured && (
                <div className="tag" style={{ position: 'absolute', top: -12, left: 32 }}>Most popular</div>
              )}
              <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.65 }}>
                {t.name}
              </div>
              <div style={{ marginTop: 20, display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <div style={{ fontFamily: 'Fraunces, serif', fontWeight: 300, fontSize: 56, letterSpacing: '-0.03em', color: t.featured ? CREAM : NAVY, lineHeight: 1 }}>
                  ${price.toLocaleString()}
                </div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, opacity: 0.6 }}>/mo</div>
              </div>
              {annual && (
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: t.featured ? CITRUS : NAVY, opacity: t.featured ? 0.9 : 0.6, marginTop: 6, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                  Billed annually · ${(price*12).toLocaleString()}/yr
                </div>
              )}
              <div style={{ fontSize: 14, marginTop: 16, opacity: 0.8 }}>{t.blurb}</div>
              <div style={{ height: 1, background: t.featured ? 'rgba(244,239,230,0.2)' : FOG, margin: '28px 0' }} />
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, fontSize: 14, lineHeight: 1.9 }}>
                {t.bullets.map((b, i) => (
                  <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                    <span style={{ color: t.featured ? CITRUS : NAVY, fontFamily: 'JetBrains Mono, monospace', marginTop: 2, fontWeight: 700 }}>✓</span>
                    <span>{b}</span>
                  </li>
                ))}
              </ul>
              <a href="contact.html" className="btn" style={{
                marginTop: 28, width: '100%', justifyContent: 'center',
                background: t.featured ? CITRUS : NAVY,
                color: NAVY,
                borderColor: t.featured ? CITRUS : NAVY,
              }}>Get started <span className="arrow">→</span></a>
              <div style={{ marginTop: 14, fontSize: 11, opacity: 0.55, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', textAlign: 'center' }}>
                + $2,500 one-time site build
              </div>
            </div>
          );
        })}
      </div>
      <style>{`@media(max-width: 900px){ .card-grid { grid-template-columns: 1fr; } }`}</style>
    </div>
  );
}

// ─── Tweaks panel ─────────────────────────────────────
function TweaksPanel() {
  const [visible, setVisible] = React.useState(false);
  const [settings, setSettings] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('psa_tweaks') || '{}'); }
    catch { return {}; }
  });
  const defaults = { hero: 'horizon', density: 'normal', art: 'on' };
  const s = { ...defaults, ...settings };

  React.useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setVisible(true);
      if (e.data?.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  React.useEffect(() => {
    localStorage.setItem('psa_tweaks', JSON.stringify(s));
    document.body.classList.toggle('dense', s.density === 'dense');
    document.body.classList.toggle('minimal', s.art === 'off');
    document.body.dataset.hero = s.hero;
    window.dispatchEvent(new CustomEvent('psa-tweaks', { detail: s }));
  }, [s.hero, s.density, s.art]);

  const update = (k, v) => setSettings(p => ({ ...p, [k]: v }));

  if (!visible) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 100,
      background: NAVY, color: CREAM, padding: 20, width: 280,
      fontFamily: 'Inter, sans-serif', boxShadow: '0 20px 50px rgba(0,0,0,0.3)',
    }}>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: CITRUS, marginBottom: 14 }}>Tweaks</div>
      <div style={{ fontFamily: 'Fraunces, serif', fontSize: 20, fontWeight: 300, marginBottom: 20 }}>Page controls</div>
      <Row label="Hero art">
        {[['Horizon', 'horizon'], ['Bars', 'bars'], ['Compass', 'compass']].map(([l, v]) => (
          <Chip key={v} active={s.hero === v} onClick={() => update('hero', v)}>{l}</Chip>
        ))}
      </Row>
      <Row label="Density">
        {[['Normal', 'normal'], ['Dense', 'dense']].map(([l, v]) => (
          <Chip key={v} active={s.density === v} onClick={() => update('density', v)}>{l}</Chip>
        ))}
      </Row>
      <Row label="Decorative art">
        {[['On', 'on'], ['Minimal', 'off']].map(([l, v]) => (
          <Chip key={v} active={s.art === v} onClick={() => update('art', v)}>{l}</Chip>
        ))}
      </Row>
    </div>
  );
}
function Row({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', opacity: 0.6, marginBottom: 8 }}>{label}</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{children}</div>
    </div>
  );
}
function Chip({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      background: active ? CITRUS : 'transparent',
      color: active ? NAVY : CREAM,
      border: `1px solid ${active ? CITRUS : 'rgba(244,239,230,0.3)'}`,
      padding: '6px 12px', fontSize: 11, cursor: 'pointer',
      fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em',
    }}>{children}</button>
  );
}

// Hook to read current hero variant (updates on tweak)
function useHeroVariant() {
  const [v, setV] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('psa_tweaks') || '{}').hero || 'horizon'; }
    catch { return 'horizon'; }
  });
  React.useEffect(() => {
    const h = (e) => setV(e.detail.hero);
    window.addEventListener('psa-tweaks', h);
    return () => window.removeEventListener('psa-tweaks', h);
  }, []);
  return v;
}

Object.assign(window, {
  PSA_NAVY: NAVY, PSA_CREAM: CREAM, PSA_CITRUS: CITRUS, PSA_SURF: SURF, PSA_FOG: FOG, PSA_GRAPH: GRAPH,
  Logo, Nav, Footer, HeroArt, ScoreDial, AuditInput, FAQ, PricingCards, TweaksPanel, useHeroVariant,
});
