/* ============ SHARED COMPONENTS ============ */

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

/* ---- Global state helpers ---- */
// Real URL routing (not hash) — required so each page can rank in Google.
// One-time migration: if the URL still has an old #/path, redirect to /path.
function useRoute() {
  const getPath = () => {
    // Migrate old hash URLs (e.g. /#/locations/anaheim) to clean paths.
    if (window.location.hash && window.location.hash.startsWith('#/')) {
      const clean = window.location.hash.slice(1);
      window.history.replaceState({}, '', clean + window.location.search);
      return clean;
    }
    return (window.location.pathname || '/') + (window.location.search || '');
  };
  const [route, setRoute] = useState(getPath);
  useEffect(() => {
    const sync = () => {
      setRoute(getPath());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('popstate', sync);
    window.addEventListener('hashchange', sync);
    return () => {
      window.removeEventListener('popstate', sync);
      window.removeEventListener('hashchange', sync);
    };
  }, []);
  return route;
}

function Link({ to, children, className, ariaLabel, ...rest }) {
  const isExternal = to.startsWith('http') || to.startsWith('tel:') || to.startsWith('mailto:');
  const href = isExternal ? to : to;
  const onClick = (e) => {
    if (isExternal) return;
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
    e.preventDefault();
    if (window.location.pathname + window.location.search === to) return;
    window.history.pushState({}, '', to);
    window.dispatchEvent(new PopStateEvent('popstate'));
  };
  return <a href={href} className={className} aria-label={ariaLabel} onClick={onClick} {...rest}>{children}</a>;
}

/* ---- Per-page <head> updates so each route can rank for its own keywords ---- */
function useDocumentHead({ title, description, canonical, jsonLd }) {
  useEffect(() => {
    if (title) document.title = title;
    const setMeta = (selector, attr, value) => {
      let el = document.head.querySelector(selector);
      if (!el) {
        el = document.createElement('meta');
        const [prop, val] = selector.replace(/[\[\]"]/g, '').split('=');
        el.setAttribute(prop, val);
        document.head.appendChild(el);
      }
      el.setAttribute(attr, value);
    };
    if (description) {
      setMeta('meta[name="description"]', 'content', description);
      setMeta('meta[property="og:description"]', 'content', description);
    }
    if (title) {
      setMeta('meta[property="og:title"]', 'content', title);
      setMeta('meta[name="twitter:title"]', 'content', title);
    }
    if (canonical) {
      let link = document.head.querySelector('link[rel="canonical"]');
      if (!link) {
        link = document.createElement('link');
        link.setAttribute('rel', 'canonical');
        document.head.appendChild(link);
      }
      link.setAttribute('href', canonical);
      setMeta('meta[property="og:url"]', 'content', canonical);
    }
    // Inject route-specific JSON-LD (and clean up on unmount)
    let scriptEl;
    if (jsonLd) {
      scriptEl = document.createElement('script');
      scriptEl.type = 'application/ld+json';
      scriptEl.dataset.routeMeta = 'true';
      scriptEl.textContent = JSON.stringify(jsonLd);
      document.head.appendChild(scriptEl);
    }
    return () => {
      if (scriptEl && scriptEl.parentNode) scriptEl.parentNode.removeChild(scriptEl);
    };
  }, [title, description, canonical, JSON.stringify(jsonLd || null)]);
}
window.useDocumentHead = useDocumentHead;

/* ---- BRAND MARK ---- */
function BrandMark({ size = 18 }) {
  return (
    <span className="brand-mark" style={{fontSize: size}}>
      <span className="brand-word">LA Maintenance<em> &amp; </em>Janitorial</span>
    </span>
  );
}

/* ---- SKIP LINK ---- */
function SkipLink() {
  return (
    <a href="#main" className="skip-link">Skip to main content</a>
  );
}

/* ---- NAV ---- */
function Nav({ route }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => { setMobileOpen(false); }, [route]);

  const is = (p) => route === p || (p !== '/' && route.startsWith(p));
  return (
    <div className="nav-wrap">
      <nav className="nav" aria-label="Primary">
        <Link to="/" className="brand" ariaLabel="LA Maintenance and Janitorial — home">
          <BrandMark/>
        </Link>
        <div className="nav-links" role="menubar">
          <Link to="/services" className={is('/services') ? 'current' : ''}>Services</Link>
          <Link to="/locations" className={is('/locations') ? 'current' : ''}>Locations</Link>
          <Link to="/about" className={is('/about') ? 'current' : ''}>About</Link>
          <Link to="/blog" className={is('/blog') ? 'current' : ''}>Resources</Link>
          <Link to="/contact" className={is('/contact') ? 'current' : ''}>Contact</Link>
        </div>
        <div className="nav-cta">
          <a href="tel:3232647800" className="nav-phone hide-sm" aria-label="Call (323) 264-7800">(323) 264-7800</a>
          <Link to="/quote" className="btn btn-accent">Get a Quote</Link>
          <button
            className="nav-mobile-btn"
            onClick={() => setMobileOpen(o => !o)}
            aria-expanded={mobileOpen}
            aria-controls="mobile-menu"
            aria-label={mobileOpen ? 'Close menu' : 'Open menu'}>
            {mobileOpen ? 'Close' : 'Menu'}
          </button>
        </div>
        <div id="mobile-menu" className={`nav-mobile-menu ${mobileOpen ? 'open' : ''}`}>
          <Link to="/services">Services</Link>
          <Link to="/locations">Locations</Link>
          <Link to="/about">About</Link>
          <Link to="/blog">Resources</Link>
          <Link to="/contact">Contact</Link>
          <Link to="/quote">Get a Quote</Link>
          <a href="tel:3232647800">Call (323) 264-7800</a>
        </div>
      </nav>
    </div>
  );
}

/* ---- TRUST BAR ---- */
function TrustBar() {
  return (
    <div className="trustbar" role="region" aria-label="Credentials">
      <div className="trustbar-inner">
        {TRUST_ITEMS.map((t, i) => (
          <div key={i} className="item"><span className="dot" aria-hidden="true"/>{t}</div>
        ))}
      </div>
    </div>
  );
}

/* ---- HERO ---- */
function Hero({ eyebrow, h1, sub, ctas, stats }) {
  return (
    <section className="hero" aria-labelledby="hero-h1">
      <div className="hero-bg" aria-hidden="true">
        <div className="hero-grid-bg"></div>
        <div className="hero-orb hero-orb-1"></div>
        <div className="hero-orb hero-orb-2"></div>
        <div className="hero-orb hero-orb-3"></div>
        <div className="hero-orb hero-orb-4"></div>
      </div>
      <div className="container">
        <div className="hero-grid">
          <div>
            {eyebrow && (
              <div className="hero-kicker">
                <span className="label-mono">{eyebrow}</span>
              </div>
            )}
            <h1 id="hero-h1" className="hero-h1">{h1}</h1>
            <p className="hero-sub">{sub}</p>
            <div className="hero-cta-row">
              {ctas.map((c, i) => (
                c.href.startsWith('tel:')
                  ? <a key={i} href={c.href} className={`btn ${c.style || 'btn-secondary'} btn-lg`}>{c.label}</a>
                  : <Link key={i} to={c.href} className={`btn ${c.style || 'btn-primary'} btn-lg`}>{c.label}</Link>
              ))}
            </div>
          </div>
          {stats && (
            <div className="hero-side" aria-label="Key numbers">
              <div className="hero-side-title">By the numbers</div>
              <div className="hero-stats">
                {stats.map((s, i) => (
                  <div key={i} className="hero-stat">
                    <div className="n">{s.n}</div>
                    <div className="l">{s.l}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ---- FINAL CTA BLOCK ---- */
function FinalCTA({
  title = "Let's make your building feel exceptional.",
  sub = "A free walkthrough, a one-page proposal, and a crew that takes real pride in the work. It starts with one conversation."
}) {
  return (
    <section className="final-cta" aria-labelledby="final-cta-h2">
      <div className="container">
        <h2 id="final-cta-h2">{title}</h2>
        <p className="lead">{sub}</p>
        <div className="hero-cta-row" style={{marginBottom: 0}}>
          <Link to="/quote" className="btn btn-primary btn-xl">Get a Quote</Link>
          <a href="tel:3232647800" className="btn btn-secondary btn-xl">Call (323) 264-7800</a>
        </div>
      </div>
    </section>
  );
}

/* ---- FAQ ---- */
function FAQBlock({ items }) {
  const [open, setOpen] = useState(0);
  return (
    <div className="faq" role="region" aria-label="Frequently asked questions">
      {items.map((it, i) => (
        <div key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
          <button
            className="faq-q"
            onClick={() => setOpen(open === i ? -1 : i)}
            aria-expanded={open === i}
            aria-controls={`faq-a-${i}`}>
            <h4>{it.q}</h4>
            <span className="plus" aria-hidden="true">+</span>
          </button>
          <div id={`faq-a-${i}`} className="faq-a" role="region">
            <p>{it.a}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---- FOOTER ---- */
function Footer() {
  return (
    <footer role="contentinfo">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <BrandMark size={22}/>
            <p>Commercial cleaning and facility care across Los Angeles and Orange County. Family-owned, over a decade in business, hundreds of buildings cared for. We care for the spaces where Southern California works, shops, heals, learns, and gathers.</p>
            <div style={{marginTop: 24, fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--body)', lineHeight: 1.7}}>
              <div style={{color:'var(--muted)', fontSize: 11, letterSpacing:'0.08em', textTransform:'uppercase', marginBottom: 8, fontWeight: 600}}>Headquarters</div>
              <div>4717 E. Washington Blvd.</div>
              <div>Commerce, CA 90040</div>
              <div style={{marginTop: 12}}><a href="tel:3232647800" style={{color:'var(--ink)', textDecoration:'none', fontWeight: 500}}>(323) 264-7800</a></div>
              <div><a href="mailto:info@californiajanitor.com" style={{color:'var(--ink)', textDecoration:'none', fontWeight: 500}}>info@californiajanitor.com</a></div>
            </div>
          </div>
          <div className="footer-col">
            <h5>Services</h5>
            <ul>
              <li><Link to="/services/commercial-office-cleaning">Office cleaning</Link></li>
              <li><Link to="/services/medical-healthcare-cleaning">Medical &amp; healthcare</Link></li>
              <li><Link to="/services/warehouse-industrial-cleaning">Warehouse &amp; industrial</Link></li>
              <li><Link to="/services/retail-shopping-center-cleaning">Retail &amp; shopping</Link></li>
              <li><Link to="/services/day-porter-services">Day porter</Link></li>
              <li><Link to="/services/green-cleaning">Green cleaning</Link></li>
              <li><Link to="/services/floor-care-strip-wax">Floor care</Link></li>
              <li><Link to="/services">All services →</Link></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>LA County</h5>
            <ul>
              {LOCATIONS_LA.slice(0, 8).map(l => (
                <li key={l.slug}><Link to={`/locations/${l.slug}`}>{l.name}</Link></li>
              ))}
              <li><Link to="/locations">All locations →</Link></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Orange County</h5>
            <ul>
              {LOCATIONS_OC.slice(0, 8).map(l => (
                <li key={l.slug}><Link to={`/locations/${l.slug}`}>{l.name}</Link></li>
              ))}
            </ul>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <ul>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/contact">Contact</Link></li>
              <li><Link to="/quote">Request a Quote</Link></li>
              <li><Link to="/blog">Resources</Link></li>
              <li><a href="tel:3232647800">(323) 264-7800</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© LA Maintenance and Janitorial Services, Inc. · Licensed, bonded, insured · Serving LA and OC for over a decade.</div>
          <div className="legal">
            <a href="#/contact">Privacy</a>
            <a href="#/contact">Terms</a>
            <a href="#/contact">Accessibility</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---- PROSE RENDERER ---- */
function Prose({ sections }) {
  return (
    <div className="prose">
      {sections.map((sec, i) => (
        <React.Fragment key={i}>
          {sec.h && <h2>{sec.h}</h2>}
          {sec.p && sec.p.map((block, j) => {
            if (typeof block === 'string') return <p key={j}>{block}</p>;
            if (block.h) return <h3 key={j}>{block.h}</h3>;
            if (block.list) return (
              <ul key={j}>
                {block.list.map((li, k) => <li key={k}>{li}</li>)}
              </ul>
            );
            if (block.note) return <div className="pullnote" key={j}>{block.note}</div>;
            return null;
          })}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---- BREADCRUMB ---- */
function Breadcrumb({ items }) {
  return (
    <nav className="page-breadcrumb" aria-label="Breadcrumb">
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span aria-hidden="true">/</span>}
          {it.href ? <Link to={it.href}>{it.label}</Link> : <span style={{color:'var(--ink)'}} aria-current="page">{it.label}</span>}
        </React.Fragment>
      ))}
    </nav>
  );
}

/* ---- TWEAKS PANEL ---- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "indigo",
  "showTrustBar": true,
  "showStats": true
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = {
  indigo:   { accent: '#635bff', ink: '#4b45c4', soft: '#e8e6ff' },
  blue:     { accent: '#2563eb', ink: '#1d4ed8', soft: '#dbe6fb' },
  green:    { accent: '#0a7c5a', ink: '#07604a', soft: '#d1ebe0' },
  teal:     { accent: '#0891b2', ink: '#0e7490', soft: '#d1eef5' },
  plum:     { accent: '#7c3aed', ink: '#6d28d9', soft: '#eadffc' }
};

function TweaksPanel({ tweaks, setTweaks, visible }) {
  if (!visible) return null;
  const set = (k, v) => setTweaks(t => ({ ...t, [k]: v }));
  return (
    <div className="tweaks-panel" role="region" aria-label="Tweaks">
      <h5><span>Tweaks</span><span className="live">● LIVE</span></h5>
      <div className="row">
        <label>Accent color</label>
        <div className="swatches">
          {Object.entries(ACCENT_OPTIONS).map(([k, v]) => (
            <button key={k} className={`sw ${tweaks.accent === k ? 'on' : ''}`}
              style={{background: v.accent}}
              onClick={() => set('accent', k)} aria-label={k}/>
          ))}
        </div>
      </div>
      <div className="row">
        <label className="chk">
          <input type="checkbox" checked={tweaks.showTrustBar}
            onChange={e => set('showTrustBar', e.target.checked)}/>
          <span>Show trust bar</span>
        </label>
      </div>
      <div className="row">
        <label className="chk">
          <input type="checkbox" checked={tweaks.showStats}
            onChange={e => set('showStats', e.target.checked)}/>
          <span>Show hero stats</span>
        </label>
      </div>
    </div>
  );
}

Object.assign(window, { useRoute, useDocumentHead, Link, Nav, TrustBar, Hero, FinalCTA, FAQBlock, Footer, Prose, Breadcrumb, TweaksPanel, TWEAK_DEFAULTS, ACCENT_OPTIONS, SkipLink, BrandMark });
