/* global React */

// ─── Logo ────────────────────────────────────────────────────
function Logo({ light = false, compact = false }) {
  return (
    <div className="logo-ring" style={{ color: light ? 'var(--bone)' : 'var(--ink)' }}>
      <img src="/assets/logo.webp" alt="Boca Tire & Auto" />
      {!compact && (
        <div className="name">
          BOCA TIRE
          <small>& AUTO SERVICE CENTER</small>
        </div>
      )}
    </div>
  );
}

// ─── Phone bar (top utility strip) ───────────────────────────
function PhoneBar({ tone = 'red' }) {
  const bg = tone === 'red' ? 'var(--red)' : 'var(--ink)';
  return (
    <div style={{
      background: bg, color: '#fff',
      fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.14em',
      textTransform: 'uppercase',
      padding: '8px 28px',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      gap: 16, flexWrap: 'wrap',
    }}>
      <span>📍 1234 N Federal Hwy · Boca Raton, FL 33432</span>
      <span style={{ display: 'flex', gap: 18 }}>
        <span>Mon–Fri 7:30a–6p · Sat 8a–3p</span>
        <a href="tel:5615550199" style={{ color: '#fff', textDecoration: 'none', fontWeight: 700 }}>
          ☎ (561) 555-0199
        </a>
      </span>
    </div>
  );
}

// ─── Services dropdown link ──────────────────────────────────
function NavLinkWithDropdown({ label, items, light }) {
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);
  const closeTimer = React.useRef(null);

  const openMenu = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpen(true);
  };
  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => setOpen(false), 120);
  };

  // close on outside click / escape
  React.useEffect(() => {
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  return (
    <div
      ref={wrapRef}
      onMouseEnter={openMenu}
      onMouseLeave={scheduleClose}
      style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}
    >
      <button
        type="button"
        className="nav-link"
        onClick={() => setOpen(o => !o)}
        aria-haspopup="menu"
        aria-expanded={open}
        style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          font: 'inherit', color: 'inherit', padding: 0,
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}
      >
        {label}
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor"
          strokeWidth="1.8" strokeLinecap="round"
          style={{ opacity: .7, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>
          <path d="M2 4l3 3 3-3" />
        </svg>
      </button>

      {open && (
        <div
          role="menu"
          style={{
            position: 'absolute',
            top: 'calc(100% + 14px)',
            left: '50%',
            transform: 'translateX(-50%)',
            minWidth: 240,
            background: light ? 'var(--ink)' : 'var(--bone)',
            color: light ? 'var(--bone)' : 'var(--ink)',
            border: '1px solid var(--ink)',
            boxShadow: '0 16px 36px -12px rgba(0,0,0,.35)',
            padding: 6,
            zIndex: 50,
          }}
        >
          {/* a small invisible bridge so the gap doesn't drop us */}
          <div aria-hidden="true" style={{
            position: 'absolute', left: 0, right: 0, top: -14, height: 14,
          }} />
          {items.map((it) => (
            <a
              key={it.label}
              href={it.href}
              role="menuitem"
              style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                padding: '12px 14px',
                textDecoration: 'none',
                color: 'inherit',
                fontFamily: 'var(--font-display)',
                fontSize: 14, letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600,
                borderBottom: '1px solid var(--line)',
                transition: 'background .12s, color .12s',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = 'var(--red)';
                e.currentTarget.style.color = '#fff';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'transparent';
                e.currentTarget.style.color = 'inherit';
              }}
            >
              <span>{it.label}</span>
              {it.meta && (
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10,
                  letterSpacing: '.12em', opacity: .7, marginLeft: 14,
                }}>{it.meta}</span>
              )}
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Nav ─────────────────────────────────────────────────────
const SERVICE_ITEMS = [
  { label: 'Brakes',       href: '/services/brakes/',     meta: 'OUR SPECIALTY' },
  { label: 'Tires',        href: '/services/tires/' },
  { label: 'Oil Change',   href: '/services/oil-change/' },
  { label: 'A/C Repair',   href: '/services/ac-repair/' },
  { label: 'Alignment',    href: '/services/' },
  { label: 'Diagnostics',  href: '/services/' },
  { label: 'Batteries',    href: '/services/' },
  { label: 'All services', href: '/services/', meta: 'VIEW ALL' },
];

function Nav({ light = false, links }) {
  const items = links || [
    { label: 'Services', dropdown: SERVICE_ITEMS },
    { label: 'About',    href: '/about/' },
    { label: 'Reviews',  href: '/reviews/' },
    { label: 'Contact',  href: '/contact/' },
  ];
  // split into two halves so logo sits centered
  const half = Math.ceil(items.length / 2);
  const leftItems = items.slice(0, half);
  const rightItems = items.slice(half);

  const renderItem = (it) => it.dropdown
    ? <NavLinkWithDropdown key={it.label} label={it.label} items={it.dropdown} light={light} />
    : <a key={it.label} href={it.href} className="nav-link">{it.label}</a>;

  const LOGO_SIZE = 132;       // visual diameter of the logo disc
  const NAV_PAD_Y = 12;        // half-height bar

  return (
    <nav style={{
      position: 'relative',
      display: 'grid',
      gridTemplateColumns: '1fr auto 1fr',
      alignItems: 'center',
      gap: 24,
      padding: `${NAV_PAD_Y}px 36px`,
      borderBottom: '1px solid var(--line)',
      background: light ? 'var(--ink)' : 'var(--bone)',
      color: light ? 'var(--bone)' : 'var(--ink)',
      zIndex: 5,
    }}>
      {/* LEFT — first half of links */}
      <div style={{ display: 'flex', gap: 28, alignItems: 'center', justifyContent: 'flex-start' }}>
        {leftItems.map(renderItem)}
      </div>

      {/* CENTER spacer — keeps grid columns balanced. Real logo is absolutely positioned below. */}
      <div style={{ width: LOGO_SIZE, height: 1 }} aria-hidden="true" />

      {/* RIGHT — remaining links + phone CTA */}
      <div style={{ display: 'flex', gap: 28, alignItems: 'center', justifyContent: 'flex-end' }}>
        {rightItems.map(renderItem)}
        <a href="tel:5615550199" className="btn btn-red" style={{ padding: '12px 18px', fontSize: 14 }}>
          ☎ (561) 555-0199
        </a>
      </div>

      {/* OVERFLOWING CENTER LOGO — disc with white stroke, hangs below the nav */}
      <a href="/" aria-label="Boca Tire & Auto — home" style={{
        position: 'absolute',
        left: '50%',
        top: '100%',
        transform: 'translate(-50%, calc(-50% - 25px))',
        width: LOGO_SIZE,
        height: LOGO_SIZE,
        borderRadius: '50%',
        background: 'var(--ink)',
        border: '6px solid var(--bone)',
        boxShadow: '0 6px 0 0 rgba(0,0,0,.06), 0 18px 28px -12px rgba(0,0,0,.35)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        textDecoration: 'none',
        zIndex: 10,
      }}>
        <img
          src="/assets/logo.webp"
          alt="Boca Tire & Auto"
          style={{ width: '88%', height: '88%', objectFit: 'contain', display: 'block' }}
        />
      </a>
    </nav>
  );
}

// ─── Trust strip (logos / certifications) ────────────────────
function TrustStrip({ dark = false }) {
  const bg = dark ? 'var(--ink)' : 'var(--bone-2)';
  const fg = dark ? 'var(--bone-3)' : 'var(--ink-2)';
  const line = dark ? 'rgba(255,255,255,.08)' : 'var(--line)';
  const items = [
    'ASE CERTIFIED', 'NAPA AUTOCARE', 'BBB A+', 'AAA APPROVED', 'TIRE RACK INSTALLER',
  ];
  return (
    <div style={{
      background: bg, color: fg,
      borderTop: `1px solid ${line}`, borderBottom: `1px solid ${line}`,
      padding: '18px 28px',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      gap: 16, flexWrap: 'wrap',
      fontFamily: 'var(--font-display)', fontSize: 14, letterSpacing: '.14em',
      textTransform: 'uppercase', fontWeight: 600,
    }}>
      {items.map((t, i) => (
        <span key={t} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span style={{
            width: 22, height: 22,
            border: `1.5px solid ${fg}`, borderRadius: '50%',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontFamily: 'var(--font-mono)',
          }}>{i + 1}</span>
          {t}
        </span>
      ))}
    </div>
  );
}

// ─── Footer ──────────────────────────────────────────────────
function Footer() {
  return (
    <footer style={{
      background: 'var(--ink)', color: 'var(--bone-3)',
      padding: '56px 28px 24px',
      fontFamily: 'var(--font-body)',
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr 1fr 1fr', gap: 36, paddingBottom: 36, borderBottom: '1px solid rgba(255,255,255,.08)' }}>
        <div>
          <Logo light />
          <p style={{ marginTop: 18, maxWidth: 320, lineHeight: 1.55, color: 'var(--bone-3)' }}>
            Family-run auto service & tire shop serving Boca Raton since 1987. Fair prices and a handshake on every job.
          </p>
          <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
            {['F', 'IG', 'G'].map(s => (
              <span key={s} style={{
                width: 34, height: 34, display: 'inline-flex',
                alignItems: 'center', justifyContent: 'center',
                border: '1px solid rgba(255,255,255,.2)',
                fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--bone)',
              }}>{s}</span>
            ))}
          </div>
        </div>
        <FooterCol title="Services" items={[
          { label: 'Brakes',     href: '/services/brakes/' },
          { label: 'Tires',      href: '/services/tires/' },
          { label: 'Oil Change', href: '/services/oil-change/' },
          { label: 'AC Repair',  href: '/services/ac-repair/' },
          { label: 'All services', href: '/services/' },
        ]} />
        <FooterCol title="Shop" items={[
          { label: 'About Us',     href: '/about/' },
          { label: 'Reviews',      href: '/reviews/' },
          { label: 'Specials',     href: '/specials/' },
          { label: 'Appointments', href: '/appointments/' },
          { label: 'Contact',      href: '/contact/' },
        ]} />
        <FooterCol title="Visit" items={[
          '1234 N Federal Hwy',
          'Boca Raton, FL 33432',
          { label: '(561) 555-0199', href: 'tel:5615550199' },
          'hello@bocatire.example',
          'Mon–Fri 7:30a–6p',
          'Sat 8a–3p · Sun closed',
        ]} />
      </div>
      <div style={{
        paddingTop: 20, display: 'flex', justifyContent: 'space-between',
        flexWrap: 'wrap', gap: 12,
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.12em',
        textTransform: 'uppercase', color: 'var(--steel)',
      }}>
        <span>© 1987–2026 Boca Tire & Auto Service Center</span>
        <span>Site by friends · Made in Boca</span>
      </div>
    </footer>
  );
}

function FooterCol({ title, items }) {
  return (
    <div>
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 12,
        letterSpacing: '.18em', textTransform: 'uppercase',
        color: 'var(--red)', marginBottom: 14,
      }}>{title}</div>
      <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items.map(it => {
          const isLink = typeof it === 'object' && it.href;
          const key = isLink ? it.label : it;
          return (
            <li key={key} style={{ color: 'var(--bone-3)', fontSize: 14 }}>
              {isLink
                ? <a href={it.href} style={{ color: 'var(--bone-3)', textDecoration: 'none', borderBottom: '1px solid transparent' }}
                     onMouseEnter={e => { e.currentTarget.style.color = 'var(--bone)'; e.currentTarget.style.borderBottomColor = 'var(--red)'; }}
                     onMouseLeave={e => { e.currentTarget.style.color = 'var(--bone-3)'; e.currentTarget.style.borderBottomColor = 'transparent'; }}>
                    {it.label}
                  </a>
                : it}
            </li>
          );
        })}
      </ul>
    </div>
  );
}

// ─── Image placeholder ───────────────────────────────────────
function Img({ label, h = 240, dark = true, style = {} }) {
  return (
    <div className={`imgph ${dark ? '' : 'bone'}`} style={{ height: h, width: '100%', ...style }}>
      <div className="imgph-inner">{label}</div>
    </div>
  );
}

// ─── Star rating ─────────────────────────────────────────────
function Stars({ n = 5, color = 'var(--red)' }) {
  return (
    <span style={{ color, letterSpacing: 2, fontSize: 14 }}>
      {'★'.repeat(n)}{'☆'.repeat(5 - n)}
    </span>
  );
}

// expose
Object.assign(window, { Logo, Nav, PhoneBar, TrustStrip, Footer, Img, Stars });
