// shared.jsx — common chrome and primitives

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

// ────────────────────────────────────────────────────────────────────────────
//  Logo
// ────────────────────────────────────────────────────────────────────────────
function HermanLogo({ size = 24, color, mark = false }) {
  if (mark) {
    return (
      <div className="brand-mark" style={{
        width: size, height: size,
        background: 'var(--ink)',
        WebkitMaskImage: 'var(--mark-src)',
        maskImage: 'var(--mask-src)',
        WebkitMaskRepeat: 'no-repeat', WebkitMaskPosition: 'center',
        WebkitMaskSize: 'contain',
      }} />
    );
  }
  return (
    <div className="brand-logo" style={{
      width: Math.round(size * 5.5), height: size,
    }} aria-label="HermanRx" role="img" />
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Pill imagery — real product photography (PNG, transparent background)
// ────────────────────────────────────────────────────────────────────────────
const PILL_SRC = {
  yellow:        'assets/pills/pill-yellow-oval.png',
  blue:          'assets/pills/pill-blue-oval.png',
  fits:          'assets/pills/pill-blue-square.png',
  sertraline:    'assets/pills/pill-lightblue-square.png',
  yellowSquare:  'assets/pills/pill-yellow-square.png',
  blueSquare:    'assets/pills/pill-blue-square.png',
  lightBlueSquare: 'assets/pills/pill-lightblue-square.png',
};

function PillArt({ kind, size = 160, alt }) {
  const src = PILL_SRC[kind] || PILL_SRC.blue;
  return (
    <img
      src={src}
      alt={alt || ''}
      style={{
        width: size, height: 'auto', maxHeight: size * 1.15,
        objectFit: 'contain',
        display: 'block',
        userSelect: 'none', pointerEvents: 'none',
      }}
      draggable={false}
    />
  );
}

// Back-compat helpers (used directly in landing hero)
function PillYellow({ size = 120 })     { return <PillArt kind="yellow" size={size} alt="Tadalafil tablet" />; }
function PillBlue({ size = 120 })       { return <PillArt kind="blue"   size={size} alt="Sildenafil tablet" />; }
function PillFits({ size = 140 })       { return <PillArt kind="fits"   size={size} alt="FITS tablet" />; }
function PillSertraline({ size = 120 }) { return <PillArt kind="sertraline" size={size} alt="Sertraline tablet" />; }

// ────────────────────────────────────────────────────────────────────────────
//  Sticky trust ribbon
// ────────────────────────────────────────────────────────────────────────────
function TrustRibbon() {
  const items = [
    "Licensed U.S. pharmacy",
    "U.S.-based physicians",
    "Discreet, unmarked packaging",
    "HIPAA-compliant care",
    "No insurance needed",
    "LegitScript-certified",
  ];
  const doubled = [...items, ...items];
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'var(--bg)',
      borderBottom: '1px solid var(--line)',
      overflow: 'hidden',
      fontSize: 11.5,
      letterSpacing: '.08em',
      textTransform: 'uppercase',
      color: 'var(--ink-dim)',
    }}>
      <div style={{
        display: 'flex',
        gap: 36,
        padding: '9px 0',
        width: 'max-content',
        animation: 'marquee 60s linear infinite',
      }}>
        {doubled.map((t, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 12, whiteSpace: 'nowrap' }}>
            <span style={{ width: 4, height: 4, borderRadius: 4, background: 'var(--accent)' }} />
            {t}
          </span>
        ))}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Top navigation
// ────────────────────────────────────────────────────────────────────────────
function TopNav({ go, current }) {
  const links = [
    { id: 'ed', label: 'ED' },
    { id: 'pe', label: 'PE' },
    { id: 'fits', label: 'FITS' },
    { id: 'how', label: 'How it works' },
    { id: 'faq', label: 'FAQ' },
  ];
  const homeClick = (e) => {
    e.preventDefault();
    if (current === 'landing') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      go('landing');
    }
  };
  return (
    <nav style={{
      position: 'sticky', top: 36, zIndex: 40,
      background: 'color-mix(in oklab, var(--bg) 86%, transparent)',
      backdropFilter: 'blur(14px)',
      WebkitBackdropFilter: 'blur(14px)',
      borderBottom: '1px solid var(--line)',
    }}>
      <div className="container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        height: 68,
      }}>
        <a href="/" onClick={homeClick}
           style={{ display: 'inline-flex', alignItems: 'center', textDecoration: 'none', color: 'inherit', cursor: 'pointer' }}
           aria-label="HermanRx home">
          <HermanLogo size={22} />
        </a>
        <div className="nav-center" style={{ display: 'flex', gap: 32, alignItems: 'center' }}>
          {links.map(l => (
            <a key={l.id} href={'#' + l.id}
               onClick={(e) => {
                 if (current !== 'landing') { e.preventDefault(); go('landing', { anchor: l.id }); }
               }}
               style={{
                 color: 'var(--ink-dim)', textDecoration: 'none', fontSize: 13.5,
                 letterSpacing: '.005em', whiteSpace: 'nowrap',
               }}>
              {l.label}
            </a>
          ))}
        </div>
        <div className="nav-right" style={{ display: 'flex', gap: 10, alignItems: 'center', whiteSpace: 'nowrap' }}>
          <a href="https://member.hermanrx.com" className="nav-signin" style={{
            color: 'var(--ink-dim)', textDecoration: 'none', fontSize: 13.5,
            whiteSpace: 'nowrap',
          }}>Sign in</a>
          <button onClick={() => go('quiz')} style={btn.solid}>
            See if you qualify
          </button>
        </div>
      </div>
    </nav>
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Buttons
// ────────────────────────────────────────────────────────────────────────────
const btn = {
  solid: {
    background: 'var(--cta)', color: 'var(--cta-ink)',
    border: '1px solid var(--cta)',
    padding: '11px 18px', borderRadius: 999,
    fontSize: 13.5, fontWeight: 500, letterSpacing: '.005em',
    transition: 'transform .12s ease, background .15s ease, opacity .15s ease',
    whiteSpace: 'nowrap',
  },
  outline: {
    background: 'transparent', color: 'var(--ink)',
    border: '1px solid var(--line-strong)',
    padding: '11px 18px', borderRadius: 999,
    fontSize: 13.5, fontWeight: 500,
    whiteSpace: 'nowrap',
  },
  ghost: {
    background: 'transparent', color: 'var(--ink-dim)',
    border: 0, padding: '11px 12px', fontSize: 13.5,
  },
  big: {
    background: 'var(--cta)', color: 'var(--cta-ink)',
    border: '1px solid var(--cta)',
    padding: '16px 28px', borderRadius: 999,
    fontSize: 15, fontWeight: 500, letterSpacing: '.005em',
    display: 'inline-flex', alignItems: 'center', gap: 10,
    whiteSpace: 'nowrap',
    transition: 'transform .12s ease, opacity .15s ease',
  },
};

// ────────────────────────────────────────────────────────────────────────────
//  Trust bar (icons under hero)
// ────────────────────────────────────────────────────────────────────────────
function TrustBar() {
  const items = [
    { ic: 'rx',        label: 'Licensed U.S. pharmacy' },
    { ic: 'doctor',    label: 'U.S.-based physicians' },
    { ic: 'box',       label: 'Discreet packaging' },
    { ic: 'shield',    label: 'HIPAA-compliant' },
    { ic: 'card',      label: 'No insurance needed' },
  ];
  return (
    <div style={{
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
    }}>
      <div className="container trustbar-grid" style={{
        display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
        gap: 0,
      }}>
        {items.map((it, i) => (
          <div key={i} style={{
            padding: '20px 12px',
            display: 'flex', alignItems: 'center', gap: 12,
            borderLeft: i === 0 ? '0' : '1px solid var(--line)',
            color: 'var(--ink-dim)',
            fontSize: 13,
          }}>
            <TrustIcon name={it.ic} />
            <span>{it.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TrustIcon({ name, size = 20 }) {
  const s = { width: size, height: size, color: 'var(--accent)', flexShrink: 0 };
  switch (name) {
    case 'rx': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M7 4h5a3 3 0 0 1 0 6H7V4z"/><path d="M7 10v10"/><path d="M10 14l7 7"/><path d="M14 14l-3 3"/>
      </svg>
    );
    case 'doctor': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/>
      </svg>
    );
    case 'box': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 7l9-4 9 4v10l-9 4-9-4V7z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>
      </svg>
    );
    case 'shield': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 3l8 3v6c0 4-3 8-8 9-5-1-8-5-8-9V6l8-3z"/>
      </svg>
    );
    case 'card': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 11h18"/><path d="M7 16h3"/>
      </svg>
    );
    case 'check': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 12l5 5L20 6"/>
      </svg>
    );
    case 'clock': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>
      </svg>
    );
    case 'lock': return (
      <svg style={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>
      </svg>
    );
    default: return null;
  }
}

// ────────────────────────────────────────────────────────────────────────────
//  Footer
// ────────────────────────────────────────────────────────────────────────────
function SiteFooter() {
  return (
    <footer style={{
      background: 'var(--bg-elev)',
      borderTop: '1px solid var(--line)',
      marginTop: 0,
      color: 'var(--ink-dim)',
    }}>
      <div className="container" style={{ padding: '64px 32px 28px' }}>
        <div className="footer-grid" style={{
          display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr',
          gap: 40, paddingBottom: 48,
          borderBottom: '1px solid var(--line)',
        }}>
          <div>
            <a href="/" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
               style={{ display: 'inline-flex', textDecoration: 'none', color: 'inherit' }}
               aria-label="HermanRx home">
              <HermanLogo size={26} />
            </a>
            <p style={{ marginTop: 18, maxWidth: 320, fontSize: 13.5, lineHeight: 1.55 }}>
              Discreet, doctor-led care for men's sexual health. Treatments shipped
              from a licensed U.S. pharmacy.
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 22, alignItems: 'center' }}>
              <LegitScriptBadge />
              <div style={{
                padding: '8px 12px', border: '1px solid var(--line)',
                borderRadius: 6, fontSize: 10.5, letterSpacing: '.12em',
                textTransform: 'uppercase', color: 'var(--ink-mute)',
              }}>HIPAA · SOC 2</div>
            </div>
          </div>
          {[
            { h: 'Treatments', l: ['Sildenafil', 'Tadalafil', 'Sertraline', 'FITS 3-in-1'] },
            { h: 'Company',    l: ['About', 'Press', 'Careers', 'Contact'] },
            { h: 'Resources',  l: ['How it works', 'Science', 'Reviews', 'Help center'] },
          ].map(col => (
            <div key={col.h}>
              <div style={{
                fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase',
                color: 'var(--ink-mute)', marginBottom: 14,
              }}>{col.h}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 10 }}>
                {col.l.map(item => (
                  <li key={item}>
                    <a href="#" onClick={(e)=>e.preventDefault()} style={{
                      color: 'var(--ink-dim)', textDecoration: 'none', fontSize: 13.5,
                    }}>{item}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="footer-bottom" style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          paddingTop: 24, fontSize: 11.5, color: 'var(--ink-mute)',
          letterSpacing: '.02em', flexWrap: 'wrap', gap: 12,
        }}>
          <span>© 2026 HermanRx Health, Inc. Prescription required. Use only as directed.</span>
          <div style={{ display: 'flex', gap: 20 }}>
            <a href="#" onClick={(e)=>e.preventDefault()} style={{ color: 'inherit' }}>Privacy</a>
            <a href="#" onClick={(e)=>e.preventDefault()} style={{ color: 'inherit' }}>Terms</a>
            <a href="#" onClick={(e)=>e.preventDefault()} style={{ color: 'inherit' }}>Telehealth consent</a>
            <a href="#" onClick={(e)=>e.preventDefault()} style={{ color: 'inherit' }}>Editorial policy</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function LegitScriptBadge() {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 12px',
      border: '1px solid var(--line)',
      borderRadius: 6,
      background: 'var(--surface)',
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--good)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 3l8 3v6c0 4-3 8-8 9-5-1-8-5-8-9V6l8-3z"/>
        <path d="M9 12l2 2 4-4"/>
      </svg>
      <div style={{ display: 'grid', lineHeight: 1.1 }}>
        <div style={{
          fontSize: 8.5, letterSpacing: '.18em', textTransform: 'uppercase',
          color: 'var(--ink-mute)',
        }}>Certified</div>
        <div style={{ fontSize: 11.5, fontWeight: 500, color: 'var(--ink)' }}>LegitScript</div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Product catalog (single source of truth)
// ────────────────────────────────────────────────────────────────────────────
const PRODUCTS = {
  fits: {
    id: 'fits',
    name: 'FITS',
    tagline: '3-in-1 sexual performance formula',
    description: 'ED + PE + arousal — one daily tablet engineered for performance, calm, and confidence.',
    pill: 'fits',
    badge: 'New',
    indication: 'ED + PE + Arousal',
    treats: ['ed','pe','arousal'],
    plans: [
      { key: '1mo', label: '1 month',   pricePerMonth: 95, total: 95,  pillsPerMonth: 30 },
      { key: '3mo', label: '3 months',  pricePerMonth: 79, total: 237, pillsPerMonth: 30, badge: 'Most popular' },
      { key: '6mo', label: '6 months',  pricePerMonth: 69, total: 414, pillsPerMonth: 30 },
      { key: '12mo',label: '12 months', pricePerMonth: 59, total: 708, pillsPerMonth: 30, badge: 'Best value' },
    ],
    comingSoon: true,
  },
  sildenafil: {
    id: 'sildenafil',
    name: 'Sildenafil',
    tagline: 'Generic Viagra — the on-demand classic',
    description: 'Take ~1 hour before; effects last 4–6 hours. Best for predictable, planned intimacy.',
    pill: 'blue',
    indication: 'On-demand ED',
    treats: ['ed'],
    doses: [
      { mg: 50,  label: '50mg' },
      { mg: 100, label: '100mg' },
    ],
    plans: [
      { key: '1mo', label: '1 month',   pricePerMonth: 49, total: 49,  pillsPerMonth: 8 },
      { key: '3mo', label: '3 months',  pricePerMonth: 38, total: 114, pillsPerMonth: 8,  badge: 'Most popular' },
      { key: '6mo', label: '6 months',  pricePerMonth: 32, total: 192, pillsPerMonth: 8 },
      { key: '12mo',label: '12 months', pricePerMonth: 26, total: 312, pillsPerMonth: 8,  badge: 'Best value' },
    ],
  },
  tadalafil: {
    id: 'tadalafil',
    name: 'Tadalafil',
    tagline: 'Generic Cialis — for daily readiness',
    description: 'A low daily dose keeps you ready whenever the moment finds you. No planning required.',
    pill: 'yellow',
    indication: 'Daily ED',
    treats: ['ed'],
    doses: [
      { mg: 2.5, label: '2.5mg daily' },
      { mg: 5,   label: '5mg daily' },
    ],
    plans: [
      { key: '1mo', label: '1 month',   pricePerMonth: 59, total: 59,  pillsPerMonth: 30 },
      { key: '3mo', label: '3 months',  pricePerMonth: 45, total: 135, pillsPerMonth: 30, badge: 'Most popular' },
      { key: '6mo', label: '6 months',  pricePerMonth: 38, total: 228, pillsPerMonth: 30 },
      { key: '12mo',label: '12 months', pricePerMonth: 32, total: 384, pillsPerMonth: 30, badge: 'Best value' },
    ],
  },
  sertraline: {
    id: 'sertraline',
    name: 'Sertraline',
    tagline: 'For lasting longer',
    description: 'A low daily dose of sertraline (25mg) is clinically used to manage premature ejaculation.',
    pill: 'sertraline',
    indication: 'Premature ejaculation',
    treats: ['pe'],
    doses: [{ mg: 25, label: '25mg daily' }],
    plans: [
      { key: '3mo', label: '3 months',  pricePerMonth: 42, total: 126, pillsPerMonth: 30, badge: 'Starter' },
      { key: '6mo', label: '6 months',  pricePerMonth: 36, total: 216, pillsPerMonth: 30, badge: 'Most popular' },
      { key: '12mo',label: '12 months', pricePerMonth: 29, total: 348, pillsPerMonth: 30, badge: 'Best value' },
    ],
  },
};

function PillArtLegacy({ kind, size }) {
  // legacy stub — superseded by image-based PillArt above
  return <PillArt kind={kind} size={size} />;
}

// ────────────────────────────────────────────────────────────────────────────
//  Reveal-on-scroll
// ────────────────────────────────────────────────────────────────────────────
function useReveal() {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); io.disconnect(); }
    }, { threshold: 0.15 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return [ref, shown];
}

function Reveal({ children, delay = 0, as: As = 'div', style, ...rest }) {
  const [ref, shown] = useReveal();
  return (
    <As ref={ref} style={{
      ...style,
      opacity: shown ? 1 : 0,
      transform: shown ? 'none' : 'translateY(14px)',
      transition: `opacity .7s ${delay}ms ease, transform .7s ${delay}ms cubic-bezier(.2,.7,.2,1)`,
    }} {...rest}>{children}</As>
  );
}

// ────────────────────────────────────────────────────────────────────────────
//  Section heading
// ────────────────────────────────────────────────────────────────────────────
function Eyebrow({ children }) {
  return (
    <div style={{
      fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase',
      color: 'var(--ink-mute)',
      display: 'inline-flex', alignItems: 'center', gap: 10,
    }}>
      <span style={{ width: 18, height: 1, background: 'var(--accent)' }} />
      {children}
    </div>
  );
}

// Export to window for cross-script access
Object.assign(window, {
  HermanLogo, PillYellow, PillBlue, PillFits, PillSertraline, PillArt,
  TrustRibbon, TopNav, TrustBar, TrustIcon, SiteFooter, LegitScriptBadge,
  Reveal, Eyebrow, PRODUCTS, btn,
});
