/* global React */
const { useState, useEffect } = React;

// ── Routing helpers ──────────────────────────────────────────
function useHashRoute() {
  const get = () => (window.location.hash.replace(/^#/, '') || '/').toLowerCase();
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const onHash = () => { setRoute(get()); window.scrollTo(0, 0); };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function go(path) { window.location.hash = path; }

function Link({ to, children, className, ...rest }) {
  const onClick = (e) => { e.preventDefault(); go(to); };
  return <a href={'#' + to} onClick={onClick} className={className} {...rest}>{children}</a>;
}

// ── Quarter math: founded 1987, started counting "compound alignment"
//    such that Q1 2026 lands on "26 quarters of compound alignment".
//    So baseline is Q3 2019. Tick once per quarter from there.
function compoundQuarters() {
  const start = new Date(2019, 6, 1); // Jul 1, 2019
  const now = new Date();
  const months = (now.getFullYear() - start.getFullYear()) * 12 + (now.getMonth() - start.getMonth());
  return Math.max(26, Math.floor(months / 3) + 1);
}

// ── Brand chrome ─────────────────────────────────────────────
function Brand({ inFooter }) {
  return (
    <Link to="/" className="brand">
      <span className="brand-mark">H</span>
      <span className="brand-name">Harswell</span>
    </Link>
  );
}

function Header({ route }) {
  const is = (p) => route === p || (p !== '/' && route.startsWith(p));
  return (
    <header className="site-header">
      <div className="container">
        <nav className="nav">
          <Brand />
          <ul className="nav-links">
            <li><Link to="/solutions" className={is('/solutions') ? 'active' : ''}>Solutions</Link></li>
            <li><Link to="/about" className={is('/about') ? 'active' : ''}>About</Link></li>
            <li><Link to="/careers" className={is('/careers') ? 'active' : ''}>Careers</Link></li>
            <li><Link to="/contact" className={is('/contact') ? 'active' : ''}>Contact</Link></li>
          </ul>
          <div className="nav-right">
            <Link to="/contact" className="btn btn-primary" style={{padding: '10px 16px', fontSize: 13}}>Request consultation</Link>
          </div>
        </nav>
      </div>
    </header>
  );
}

function Footer() {
  const q = compoundQuarters();
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Brand />
            <p style={{marginTop: 16}}>
              Aligned outcomes for the modern enterprise. A public benefit corporation since 1987.
            </p>
          </div>
          <div>
            <h4>Solutions</h4>
            <ul>
              <li><Link to="/solutions#cadence">Cadence Solutions</Link></li>
              <li><Link to="/solutions#stewardship">Stewardship Platform</Link></li>
              <li><Link to="/solutions#reabsorption">Reabsorption Services</Link></li>
              <li><Link to="/solutions">Brand Alignment</Link></li>
              <li><Link to="/solutions">Continuity Architecture</Link></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/about#leadership">Leadership</Link></li>
              <li><Link to="/about#values">Values</Link></li>
              <li><Link to="/careers">Careers</Link></li>
              <li><Link to="/contact">Contact</Link></li>
            </ul>
          </div>
          <div>
            <h4>Resources</h4>
            <ul>
              <li><a href="archive.html#heinz">Customer stories</a></li>
              <li><a href="archive.html#manual9">Whitepapers</a></li>
              <li><a href="archive.html#allhands">Press</a></li>
              <li><a href="archive.html#br04">Partner program</a></li>
            </ul>
          </div>
          <div>
            <h4>Compliance</h4>
            <ul>
              <li><Link to="/privacy">Privacy</Link></li>
              <li><Link to="/terms">Terms of service</Link></li>
              <li><a href="#" onClick={(e)=>e.preventDefault()}>SOC 2 / ISO 27001</a></li>
              <li><a href="#" onClick={(e)=>e.preventDefault()}>Accessibility</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 1987–{new Date().getFullYear()} Harswell, PBC. All rights reserved. {q} quarters of compound alignment.</div>
          <div style={{display: 'flex', gap: 18}}>
            <a href="#" onClick={(e)=>e.preventDefault()}>Status</a>
            <a href="#" onClick={(e)=>e.preventDefault()}>Trust center</a>
            <Link to="/portal" className="footer-internal">Internal</Link>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ── Generic photo placeholder ────────────────────────────────
// Maps each known label to a stable Unsplash photo. If the image fails to load,
// the gradient block (set by tone) remains as a graceful fallback.
const STOCK_IMG = {
  'Hero · glass-walled office':        '1497366216548-37526070297c',
  "Founders' office, c. 1987":         '1497366754035-f200968a6e72',
  'Cadence dashboard · partner view':  '1551288049-bebda4e38f71',
  'Stewardship review · quarterly':    '1543269865-cbf427effbad',
  'Reabsorption engagement · field':   '1497366811353-6870744d04b2',
  'Voice governance · review':         '1486312338219-ce68d2c6f44d',
  'Continuity blueprint':              '1454165804606-c3d57bc86b40',
  'Harswell HQ · stewardship floor':   '1497215842964-222b430dc094',
};

function Stock({ tone, ratio = 'wide', label, style }) {
  const cls = `stock stock-${ratio} ${tone === 'warm' ? 'stock-warm' : tone === 'cool' ? 'stock-cool' : tone === 'deep' ? 'stock-deep' : ''}`;
  const id = STOCK_IMG[label];
  const src = id ? `https://images.unsplash.com/photo-${id}?w=1200&q=70&auto=format&fit=crop` : null;
  const onErr = (e) => { e.currentTarget.style.display = 'none'; };
  return (
    <div className={cls} style={style}>
      {src && (
        <img
          src={src}
          alt={label}
          loading="lazy"
          onError={onErr}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
        />
      )}
      {/* Original placeholder label preserved as a visually-hidden label for source-readers */}
      <span className="stock-label" style={{ position: 'absolute', width: 1, height: 1, padding: 0, margin: -1, overflow: 'hidden', clip: 'rect(0,0,0,0)', whiteSpace: 'nowrap', border: 0 }}>{label}</span>
    </div>
  );
}

// ── Fake but plausible client logos ──────────────────────────
function ClientLogo({ kind }) {
  // Generic shape + neutral wordmark. Greyed out via opacity.
  const items = {
    chevron: { mark: <polygon points="6,18 18,6 30,18 18,30" />, name: 'NORDLINE' },
    rings:   { mark: <g><circle cx="14" cy="18" r="9" fill="none" strokeWidth="2.5"/><circle cx="22" cy="18" r="9" fill="none" strokeWidth="2.5"/></g>, name: 'Brevikorp' },
    bars:    { mark: <g><rect x="6" y="8" width="4" height="20"/><rect x="13" y="14" width="4" height="14"/><rect x="20" y="4" width="4" height="24"/><rect x="27" y="11" width="4" height="17"/></g>, name: 'AXIOMERA' },
    triangle:{ mark: <polygon points="18,4 32,30 4,30" fill="none" strokeWidth="2.5"/>, name: 'Vanthorpe' },
    hex:     { mark: <polygon points="18,4 31,12 31,24 18,32 5,24 5,12" fill="none" strokeWidth="2.5"/>, name: 'KESTRELCO' },
    dots:    { mark: <g><circle cx="9" cy="18" r="3"/><circle cx="18" cy="18" r="3"/><circle cx="27" cy="18" r="3"/></g>, name: 'Lindemark' },
    arrow:   { mark: <path d="M4 18 L26 18 L20 12 M26 18 L20 24" fill="none" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>, name: 'Foroval' },
    square:  { mark: <g><rect x="6" y="6" width="11" height="11"/><rect x="19" y="19" width="11" height="11" fill="none" strokeWidth="2.5"/></g>, name: 'CONTRA·M' },
  };
  const it = items[kind];
  return (
    <svg viewBox="0 0 160 36" xmlns="http://www.w3.org/2000/svg" aria-label={it.name}>
      <g fill="#1A1A1F" stroke="#1A1A1F" transform="translate(0,0)">{it.mark}</g>
      <text x="42" y="24" fontFamily="Inter, Helvetica, Arial, sans-serif" fontSize="15" fontWeight="600" letterSpacing="0.03em" fill="#1A1A1F">{it.name}</text>
    </svg>
  );
}

// ── Solution icon (geometric, generic) ───────────────────────
function SolutionIcon({ kind }) {
  const stroke = '#2A3A52';
  const props = { width: 22, height: 22, viewBox: '0 0 24 24', fill: 'none', stroke, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'cadence') return (
    <svg {...props}><path d="M3 12h3l2-6 4 12 2-9 2 6 2-3h3"/></svg>
  );
  if (kind === 'stewardship') return (
    <svg {...props}><path d="M12 3l8 3v6c0 4.5-3.5 8-8 9-4.5-1-8-4.5-8-9V6l8-3z"/><path d="M9 12l2 2 4-4"/></svg>
  );
  if (kind === 'reabsorption') return (
    <svg {...props}><circle cx="12" cy="12" r="8"/><path d="M12 4v8l4 2"/></svg>
  );
  if (kind === 'brand') return (
    <svg {...props}><rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 9h18M8 14h8"/></svg>
  );
  if (kind === 'continuity') return (
    <svg {...props}><path d="M4 12c0-4 3-7 8-7s8 3 8 7-3 7-8 7"/><path d="M9 12l-3 3-3-3"/></svg>
  );
  return null;
}

window.HW = { useHashRoute, go, Link, Brand, Header, Footer, Stock, ClientLogo, SolutionIcon, compoundQuarters };
