// Overtime Agency, shared chrome: Nav, CartDrawer, Footer
const { Button, Badge } = window.OvertimeDesignSystem_c395fa;
window.OT_defineHooks();

const NAV_LINKS = [
  ['Home', 'index.html'],
  ['Services', 'services.html'],
  ['Pricing', 'pricing.html'],
  ['About', 'about.html'],
];

function CartIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="8" cy="21" r="1"></circle><circle cx="19" cy="21" r="1"></circle>
      <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"></path>
    </svg>
  );
}

function OTNav({ page, onOpenCart }) {
  const items = useCart();
  const [menu, setMenu] = React.useState(false);
  const [leaving, setLeaving] = React.useState(null);
  React.useEffect(() => {
    // Scroll lock: freeze the page behind the menu and stop scroll chaining
    if (menu) {
      document.documentElement.style.overflow = 'hidden';
      document.body.style.overflow = 'hidden';
      document.documentElement.style.overscrollBehavior = 'none';
    } else {
      document.documentElement.style.overflow = '';
      document.body.style.overflow = '';
      document.documentElement.style.overscrollBehavior = '';
    }
    return () => {
      document.documentElement.style.overflow = '';
      document.body.style.overflow = '';
      document.documentElement.style.overscrollBehavior = '';
    };
  }, [menu]);
  const go = (href) => (e) => {
    e.preventDefault();
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { window.location.href = href; return; }
    setLeaving(href);
    setTimeout(() => { window.location.href = href; }, 340);
  };
  return (
    <React.Fragment>
      <nav className="ot-nav">
        <div className="ot-wrap ot-nav-inner">
          <a href="index.html" style={{ textDecoration: 'none', display: 'flex', alignItems: 'center', whiteSpace: 'nowrap' }} aria-label="Overtime Agency, home">
            <img src="assets/wordmark-red.png" alt="Overtime Agency" style={{ height: 38, width: 'auto', display: 'block' }} />
          </a>
          <div className="ot-nav-links">
            {NAV_LINKS.map(([label, href]) => (
              <a key={href} href={href} className={'ot-nav-link' + (page === href ? ' active' : '')}>{label}</a>
            ))}
            <Button size="sm" onClick={() => { window.location.href = 'book.html'; }}>Book a call</Button>
          </div>
          <button className="ot-cartbtn" aria-label="Cart" onClick={() => { setMenu(false); onOpenCart(); }}>
            <CartIcon />
            {items.length > 0 && <span className="count">{items.length}</span>}
          </button>
          <button className="ot-burger" aria-label={menu ? 'Close menu' : 'Menu'} aria-expanded={menu} onClick={() => setMenu(m => !m)}>
            {menu
              ? <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M2 2l12 12M14 2L2 14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
              : <React.Fragment><span></span><span></span><span></span></React.Fragment>}
          </button>
        </div>
      </nav>
      {menu && (
        <div className={'ot-mobile-menu' + (leaving ? ' leaving' : '')}>
          <nav aria-label="Site">
            {[...NAV_LINKS, ['Book a call', 'book.html']].map(([label, href], i) => (
              <a key={href} href={href} onClick={go(href)}
                className={(page === href ? 'active' : '') + (leaving === href ? ' hit' : '') + (leaving && leaving !== href ? ' dim' : '')}
                style={{ animationDelay: (i * 45) + 'ms' }}>
                <span className="idx">{'0' + (i + 1)}</span>
                {label}
                <span className="go" aria-hidden="true">→</span>
              </a>
            ))}
          </nav>
          <div className={'ot-menu-audit' + (leaving ? ' dim' : '')}>
            <div>
              <div className="k">5 free audits available this month</div>
              <div className="t">Find your leaks. Free, in writing.</div>
            </div>
            <Button variant="inverse" fullWidth onClick={() => { window.location.href = 'book.html'; }}>Get your free audit</Button>
          </div>
          <div className={'ot-menu-foot' + (leaving ? ' dim' : '')}>
            <button className="ot-menu-cartbtn" onClick={() => { setMenu(false); onOpenCart(); }}>
              <CartIcon />
              Cart{items.length > 0 ? ` (${items.length})` : ', empty'}
            </button>
            <div className="ot-menu-meta">
              <div className="ot-menu-social">
                <a href="https://instagram.com/otagency" aria-label="Instagram" onClick={(e) => e.preventDefault()} title="Instagram, add your profile URL">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <rect x="2" y="2" width="20" height="20" rx="5"></rect>
                    <circle cx="12" cy="12" r="4"></circle>
                    <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"></circle>
                  </svg>
                </a>
                <a href="https://facebook.com/otagency" aria-label="Facebook" onClick={(e) => e.preventDefault()} title="Facebook, add your page URL">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"></path>
                  </svg>
                </a>
                <a href="https://google.com/business" aria-label="Google Business Profile" onClick={(e) => e.preventDefault()} title="Google, add your Business Profile URL">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M12 21a9 9 0 1 1 6.36-15.36"></path>
                    <path d="M21 12h-9"></path>
                  </svg>
                </a>
              </div>
              <div className="ot-menu-emails">
                {window.OT_DATA.site.emails.map(e => <a key={e} href={'mailto:' + e}>{e}</a>)}
              </div>
            </div>
            <div className="ot-menu-tagline">{window.OT_DATA.site.tagline}</div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

function CartDrawer({ open, onClose }) {
  const items = useCart();
  const D = window.OT_DATA;
  if (!open) return null;
  const totals = window.OT_CART.totals();
  const hasAudit = items.some(i => i.kind === 'audit');
  const paid = items.filter(i => i.kind !== 'audit');
  return (
    <React.Fragment>
      <div className="ot-scrim" onClick={onClose}></div>
      <aside className="ot-drawer" role="dialog" aria-label="Cart">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--border-default)' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 26, textTransform: 'uppercase' }}>Your cart</span>
          <button onClick={onClose} aria-label="Close cart" style={{ background: 'none', border: 'none', cursor: 'pointer', font: '600 14px var(--font-body)', color: 'var(--text-body)', padding: 8 }}>✕ Close</button>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {items.length === 0 && (
            <div style={{ padding: '48px 0', textAlign: 'center' }}>
              <p className="ot-lede" style={{ marginBottom: 20 }}>Nothing in here yet.</p>
              <Button variant="secondary" onClick={() => { window.location.href = 'pricing.html'; }}>See the packages</Button>
            </div>
          )}
          {items.map(item => {
            const isBundle = item.kind === 'bundle';
            const rec = isBundle ? D.bundleById[item.id] : item.kind === 'service' ? D.serviceById[item.id] : D.audit;
            return (
              <div key={item.id} style={{ border: '1px solid var(--border-default)', borderRadius: 8, background: 'var(--surface-card)', padding: '16px 18px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline' }}>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 18, textTransform: 'uppercase' }}>{rec.name}</span>
                  <button onClick={() => window.OT_CART.remove(item.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', font: '600 12px var(--font-body)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Remove</button>
                </div>
                {item.kind === 'audit' ? (
                  <div style={{ marginTop: 6, font: 'var(--type-body-sm)', color: 'var(--text-secondary)' }}>
                    <s style={{ color: 'var(--text-muted)' }}>{D.fmt(D.audit.regular)}</s>{' '}<strong style={{ color: 'var(--ot-red)' }}>Free this month</strong>
                  </div>
                ) : (
                  <div style={{ marginTop: 6, font: 'var(--type-body-sm)', color: 'var(--text-secondary)' }}>
                    {D.range(rec.setup)} setup · {D.range(rec.monthly)}/mo
                  </div>
                )}
                {isBundle && <div style={{ marginTop: 6, font: 'var(--type-caption)', color: 'var(--text-muted)' }}>{rec.includes.map(id => D.serviceById[id].name).join(' + ')}</div>}
              </div>
            );
          })}
        </div>
        {items.length > 0 && (
          <div style={{ borderTop: '2px solid var(--ot-ink)', padding: '18px 24px 24px', background: 'var(--surface-page)' }}>
            {paid.length > 0 && (
              <React.Fragment>
                <div style={{ display: 'flex', justifyContent: 'space-between', font: 'var(--type-body-sm)', color: 'var(--text-secondary)', marginBottom: 6 }}>
                  <span>Estimated setup</span><strong style={{ color: 'var(--text-body)' }}>{D.range(totals.setup)}</strong>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', font: 'var(--type-body-sm)', color: 'var(--text-secondary)', marginBottom: 14 }}>
                  <span>Estimated monthly</span><strong style={{ color: 'var(--text-body)' }}>{D.range(totals.monthly)}/mo</strong>
                </div>
              </React.Fragment>
            )}
            {hasAudit && paid.length === 0 && (
              <div style={{ font: 'var(--type-body-sm)', color: 'var(--text-secondary)', marginBottom: 14 }}>Free Trade Audit, no charge, ever.</div>
            )}
            <Button size="lg" onClick={() => { window.location.href = 'checkout.html'; }} style={{ width: '100%' }}>Continue to checkout</Button>
            <div style={{ font: 'var(--type-caption)', color: 'var(--text-muted)', marginTop: 10, textAlign: 'center' }}>
              No payment today, checkout books your kickoff call.
            </div>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
}

function SocialIcons({ className }) {
  return (
    <div className={className || 'ot-foot-social'}>
      <a href="https://instagram.com/otagency" aria-label="Instagram" onClick={(e) => e.preventDefault()} title="Instagram, add your profile URL">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <rect x="2" y="2" width="20" height="20" rx="5"></rect>
          <circle cx="12" cy="12" r="4"></circle>
          <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"></circle>
        </svg>
      </a>
      <a href="https://facebook.com/otagency" aria-label="Facebook" onClick={(e) => e.preventDefault()} title="Facebook, add your page URL">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"></path>
        </svg>
      </a>
      <a href="https://google.com/business" aria-label="Google Business Profile" onClick={(e) => e.preventDefault()} title="Google, add your Business Profile URL">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M12 21a9 9 0 1 1 6.36-15.36"></path>
          <path d="M21 12h-9"></path>
        </svg>
      </a>
    </div>
  );
}

function OTFooter() {
  const D = window.OT_DATA;
  const year = new Date().getFullYear();
  return (
    <footer className="ot-band-ink">
      {/* CTA band */}
      <div className="ot-wrap ot-foot-cta">
        <div>
          <div className="ot-kicker" style={{ color: 'var(--ot-red-bright)', marginBottom: 16 }}>{D.audit.scarcity}</div>
          <div className="ot-display" style={{ color: 'var(--ot-cream)', fontSize: 'clamp(42px, 6.5vw, 88px)', lineHeight: 0.92 }}>
            Ready to put your<br />business in overtime?
          </div>
        </div>
        <div className="ot-cta-row ot-foot-cta-btns">
          <Button size="lg" variant="inverse" onClick={() => { window.location.href = 'book.html'; }}>Get your free audit</Button>
          <Button size="lg" onClick={() => { window.location.href = 'pricing.html'; }}>See the packages</Button>
        </div>
      </div>

      {/* Link columns */}
      <div className="ot-wrap">
        <div className="ot-foot-grid">
          <div className="ot-foot-brand">
            <img src="assets/wordmark-cream.png" alt="Overtime Agency" style={{ width: 'min(230px, 60vw)', height: 'auto' }} />
            <p style={{ font: 'var(--type-body-sm)', color: 'var(--ot-cream)', opacity: 0.65, margin: '16px 0 18px', maxWidth: 300 }}>
              {D.site.oneliner} Built for HVAC, plumbing, electrical, roofing and construction, nobody else.
            </p>
            <SocialIcons />
          </div>
          <div>
            <div className="ot-foot-h">Explore</div>
            <a className="ot-foot-link" href="index.html">Home</a>
            <a className="ot-foot-link" href="services.html">Services</a>
            <a className="ot-foot-link" href="pricing.html">Pricing</a>
            <a className="ot-foot-link" href="about.html">About</a>
            <a className="ot-foot-link" href="book.html">Book a call</a>
          </div>
          <div>
            <div className="ot-foot-h">The systems</div>
            {D.services.map(s => (
              <a key={s.id} className="ot-foot-link" href={'services.html#' + s.id}>{({ storefront: 'Digital Storefront', recovery: 'Revenue Recovery', trust: 'Trust Engine', reactivation: 'Reactivation Engine' })[s.id]}</a>
            ))}
            <a className="ot-foot-link" href="services.html#audit" style={{ color: 'var(--ot-red-bright)', opacity: 1 }}>The Free Trade Audit</a>
          </div>
          <div>
            <div className="ot-foot-h">Talk to a person</div>
            {D.site.emails.map(e => (
              <a key={e} className="ot-foot-link" href={'mailto:' + e}>{e}</a>
            ))}
            <span className="ot-foot-link" style={{ cursor: 'default' }}>{D.site.domain}</span>
            <p style={{ font: 'var(--type-caption)', color: 'var(--ot-cream)', opacity: 0.5, margin: '14px 0 0', maxWidth: 220 }}>
              Phones on your mind at 2am? The chat in the corner never sleeps.
            </p>
          </div>
        </div>
      </div>

      {/* Legal bar */}
      <div className="ot-foot-bar">
        <div className="ot-wrap ot-foot-bar-inner">
          <img src="assets/mark-cream.png" alt="" style={{ height: 26, width: 'auto', opacity: 0.85 }} />
          <span>© {year} Overtime Agency · {D.site.domain}</span>
          <span className="ot-foot-tag">{D.site.tagline}</span>
        </div>
      </div>
    </footer>
  );
}

// Shared "Why we're different" section, used on Home and About
function OTDifferent() {
  const D = window.OT_DATA;
  return (
    <section className="ot-band-ink" data-screen-label="Why we're different">
      <div className="ot-wrap ot-section">
        <div className="ot-kicker" style={{ color: 'var(--ot-red-bright)', marginBottom: 20 }}>Why we're different</div>
        <div className="diff-head">
          <h2 className="ot-display ot-h2" style={{ color: 'var(--ot-cream)', maxWidth: 640 }}>We are not another marketing agency.</h2>
          <p style={{ font: 'var(--type-body)', color: 'var(--ot-cream)', opacity: 0.65, maxWidth: 380, margin: 0 }}>
            Contractors have been burned by agencies that overpromise and underdeliver. Hold us to the receipts instead.
          </p>
        </div>
        <div className="diff-cols" aria-hidden="true">
          <span>What you've been sold</span>
          <span>What we install instead</span>
        </div>
        <div className="diff-rows">
          {D.different.map((d, i) => (
            <div key={i} className="diff-row">
              <div className="diff-no">
                <span className="x">✕</span>
                <span className="t">{d.no}</span>
              </div>
              <div className="diff-yes">
                <div className="y">{d.yes}</div>
                <p className="p">{d.proof}</p>
              </div>
            </div>
          ))}
        </div>
        <div className="diff-foot">
          <span className="ot-micro" style={{ color: 'var(--ot-cream)', opacity: 0.6 }}>
            Don't take our word for it, the free audit puts the proof on paper.
          </span>
          <Button variant="inverse" onClick={() => { window.location.href = 'book.html'; }}>Get the proof, free audit</Button>
        </div>
      </div>
    </section>
  );
}

// Page shell: nav + cart drawer + footer + chatbot mount
function OTShell({ page, children, hideFooterCta }) {
  const [cartOpen, setCartOpen] = React.useState(false);
  React.useEffect(() => {
    window.OT_openCart = () => setCartOpen(true);
    return () => { delete window.OT_openCart; };
  }, []);
  return (
    <React.Fragment>
      <OTNav page={page} onOpenCart={() => setCartOpen(true)} />
      {children}
      <OTFooter />
      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} />
      <OTChat />
    </React.Fragment>
  );
}

// Shared commitments band — the risk-reversal the rest of the category doesn't offer.
function OTPromise({ heading }) {
  const items = [
    ['Month-to-month', 'Fire us any month. No lock-in, no cancellation maze.'],
    ['You own everything', 'Website, number, reviews, accounts, all in your name.'],
    ['No shared leads', 'Your own calls. Never resold to five other shops in your zip.'],
    ['Real prices, shown', 'Ranges right on the site. No "call for a quote."'],
  ];
  return (
    <section className="ot-wrap" data-screen-label="Our promises">
      {heading && <h2 className="ot-display ot-h2" style={{ marginBottom: 28 }}>{heading}</h2>}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 20, borderTop: '2px solid var(--ot-ink)', borderBottom: '2px solid var(--ot-ink)', padding: '24px 0' }}>
        {items.map(([t, d]) => (
          <div key={t}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(17px, 1.6vw, 21px)', textTransform: 'uppercase', color: 'var(--ot-red)', lineHeight: 1.05 }}>{t}</div>
            <p style={{ font: 'var(--type-body-sm)', color: 'var(--text-secondary)', margin: '9px 0 0' }}>{d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { OTNav, OTFooter, CartDrawer, OTShell, OTDifferent, OTPromise });
