// Shared brand + chrome components

// Bespoke monogram: a serif "T" whose horizontal bar doubles as a balanced
// scale — two arms suspended from a single, level beam. Reads as initial,
// instrument, and equilibrium in one mark.
const BrandMark = ({ size = 32, color = 'var(--navy)', accent = 'var(--gold)' }) => (
  <svg width={size} height={size} viewBox="0 0 40 40" fill="none" aria-label="Tailored Mediation">
    {/* engraved hairline frame */}
    <rect x="0.5" y="0.5" width="39" height="39" stroke={color} strokeOpacity="0.18" strokeWidth="1"/>
    {/* fulcrum / pivot */}
    <line x1="20" y1="8" x2="20" y2="13" stroke={color} strokeWidth="1.4" strokeLinecap="square"/>
    {/* the beam — slight serif ends */}
    <path d="M5 13 L35 13" stroke={color} strokeWidth="1.4" strokeLinecap="square"/>
    <path d="M5 12 L5 14 M35 12 L35 14" stroke={color} strokeWidth="1.4"/>
    {/* suspension lines */}
    <line x1="9" y1="13" x2="9" y2="22" stroke={color} strokeWidth="0.8"/>
    <line x1="31" y1="13" x2="31" y2="22" stroke={color} strokeWidth="0.8"/>
    {/* pans — one slightly weighted to suggest deliberation, both within balance */}
    <path d="M5 22 L13 22 L11 26 L7 26 Z" stroke={color} strokeWidth="1" fill="none"/>
    <path d="M27 22 L35 22 L33 26 L29 26 Z" stroke={color} strokeWidth="1" fill="none"/>
    {/* the stem of the T (descending serif) */}
    <line x1="20" y1="14" x2="20" y2="33" stroke={color} strokeWidth="1.4"/>
    <path d="M17 33 L23 33" stroke={color} strokeWidth="1.4" strokeLinecap="square"/>
    {/* accent node at the fulcrum */}
    <circle cx="20" cy="13" r="2" fill={accent}/>
  </svg>
);

const Brand = ({ onNav }) => (
  <a className="brand" onClick={() => onNav('home')} style={{ cursor: 'pointer' }}>
    <BrandMark size={32}/>
    <div className="brand-name">Tailored<em style={{ color: 'var(--slate-700)' }}>Mediation</em></div>
  </a>
);

// NAV — top bar with hover dropdowns and a richer mega-menu under "Explore".
// Both the trigger anchor and the dropdown panel sit in a single hover region;
// a small close-delay keeps the menu forgiving.

// Single-column hover dropdown (used for About, Practice). Click on the trigger
// navigates to `triggerId`; hover surfaces a list of related sub-pages.
const NavMini = ({ label, page, onNav, items, triggerId, groupPages }) => {
  const { useState, useRef, useEffect } = React;
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const closeTimer = useRef(null);
  const isActive = (groupPages || [triggerId]).includes(page);

  const cancelClose = () => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
  };
  const scheduleClose = (delay = 220) => {
    cancelClose();
    closeTimer.current = setTimeout(() => setOpen(false), delay);
  };

  useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      cancelClose();
    };
  }, []);

  return (
    <div className="nav-dd" ref={ref}
         onMouseEnter={() => { cancelClose(); setOpen(true); }}
         onMouseLeave={() => scheduleClose()}>
      <a className={`nav-link ${isActive ? 'active' : ''}`}
         onClick={() => { onNav(triggerId); setOpen(false); }}
         style={{ cursor: 'pointer' }}>
        {label} <span style={{ fontSize: 9, marginLeft: 4, opacity: 0.7 }}>▾</span>
      </a>
      {open && (
        <div className="nav-mini-outer"
             onMouseEnter={cancelClose}
             onMouseLeave={() => scheduleClose()}>
          <div className="nav-mini">
            {items.map(i => (
              <a key={i.id}
                 className={`nav-mini-item ${page === i.id ? 'active' : ''}`}
                 onClick={() => { onNav(i.id); setOpen(false); cancelClose(); }}>
                <span className="nav-mini-label">{i.label}</span>
                {i.sub && <span className="nav-mini-sub">{i.sub}</span>}
              </a>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

const NavMega = ({ label, page, onNav, sections, groupPages }) => {
  const { useState, useRef, useEffect } = React;
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const closeTimer = useRef(null);
  const isActive = groupPages.includes(page);

  const cancelClose = () => {
    if (closeTimer.current) {
      clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
  };
  const scheduleClose = (delay = 220) => {
    cancelClose();
    closeTimer.current = setTimeout(() => setOpen(false), delay);
  };

  useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      cancelClose();
    };
  }, []);

  return (
    <div className="nav-dd" ref={ref}
         onMouseEnter={() => { cancelClose(); setOpen(true); }}
         onMouseLeave={() => scheduleClose()}>
      <a className={`nav-link ${isActive || page === 'explore' ? 'active' : ''}`}
         onClick={() => { onNav('explore'); setOpen(false); }}
         style={{ cursor: 'pointer' }}>
        {label} <span style={{ fontSize: 9, marginLeft: 4, opacity: 0.7 }}>▾</span>
      </a>
      {open && (
        <div className="nav-mega-outer"
             onMouseEnter={cancelClose}
             onMouseLeave={() => scheduleClose()}>
          <div className="nav-mega">
            {sections.map(s => (
              <div key={s.title} className="nav-mega-col">
                <div className="nav-mega-title">{s.title}</div>
                {s.items.map(i => (
                  <a key={i.id}
                     className={`nav-mega-item ${page === i.id ? 'active' : ''}`}
                     onClick={() => { onNav(i.id); setOpen(false); cancelClose(); }}>
                    <span className="nav-mega-label">{i.label}</span>
                    {i.sub && <span className="nav-mega-sub">{i.sub}</span>}
                  </a>
                ))}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

const Nav = ({ page, onNav }) => {
  const { useState, useEffect } = React;
  const [drawerOpen, setDrawerOpen] = useState(false);

  // Sections rendered both in the desktop mega-menu and in the mobile drawer.
  const exploreSections = [
    {
      title: 'About',
      items: [
        { id: 'about', label: 'Daniel B. Garrie', sub: 'Biography & credentials' },
        { id: 'what-is', label: 'What is Tailored Mediation', sub: 'The model, explained' },
        { id: 'tailored-vs-standard', label: 'Tailored vs. Standard', sub: 'Side-by-side comparison' },
      ],
    },
    {
      title: 'Practice',
      items: [
        { id: 'mediation', label: 'Mediation', sub: 'Privately-administered' },
        { id: 'special-master', label: 'Special Master', sub: 'Court-appointed discovery referee' },
        { id: 'forensic-neutral', label: 'Forensic Neutral', sub: 'Independent technical expert' },
        { id: 'ai-disputes', label: 'AI Disputes', sub: 'Tribunal services' },
        { id: 'arbitration', label: 'Arbitration', sub: 'Sole or panel' },
        { id: 'process', label: 'Process & Methodology', sub: 'Phase-by-phase' },
        { id: 'notable-matters', label: 'Notable Matters', sub: 'Anonymized representative work' },
        { id: 'engagement-terms', label: 'Engagement Terms', sub: 'How retention works' },
      ],
    },
    {
      title: 'Writing & Voice',
      items: [
        { id: 'insights', label: 'Insights', sub: 'Articles from the practice' },
        { id: 'publications', label: 'Publications & Books', sub: '20+ books, 300+ articles' },
        { id: 'speaking', label: 'Speaking', sub: '600+ presentations' },
        { id: 'faq', label: 'FAQ', sub: 'Practical answers for counsel' },
      ],
    },
  ];
  const exploreGroup = exploreSections.flatMap(s => s.items.map(i => i.id));

  // Lock background scroll while the drawer is open and close on ESC.
  useEffect(() => {
    if (!drawerOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setDrawerOpen(false); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [drawerOpen]);

  const go = (id) => { onNav(id); setDrawerOpen(false); };

  const item = (id, label) => (
    <a key={id} className={`nav-link ${page === id ? 'active' : ''}`}
       onClick={() => onNav(id)} style={{ cursor: 'pointer' }}>{label}</a>
  );

  return (
    <nav className="nav">
      <div className="nav-inner">
        <Brand onNav={onNav}/>

        {/* Desktop links */}
        <div className="nav-links nav-links-desktop">
          {item('home', 'Home')}
          <NavMini label="About" page={page} onNav={onNav}
                   triggerId="about"
                   groupPages={exploreSections[0].items.map(i => i.id)}
                   items={exploreSections[0].items}/>
          <NavMini label="Practice" page={page} onNav={onNav}
                   triggerId="services"
                   groupPages={['services', ...exploreSections[1].items.map(i => i.id)]}
                   items={exploreSections[1].items}/>
          {item('insights', 'Insights')}
          <NavMega label="Explore" page={page} onNav={onNav}
                   sections={exploreSections} groupPages={exploreGroup}/>
          {item('contact', 'Contact')}
          <button className="nav-cta" onClick={() => onNav('intake')}>
            Begin a matter <span style={{ fontSize: 11 }}>→</span>
          </button>
        </div>

        {/* Mobile hamburger */}
        <button className="nav-toggle" aria-label={drawerOpen ? 'Close menu' : 'Open menu'}
                aria-expanded={drawerOpen}
                onClick={() => setDrawerOpen(!drawerOpen)}>
          <span className={`nav-toggle-bars ${drawerOpen ? 'open' : ''}`}>
            <span/><span/><span/>
          </span>
        </button>
      </div>

      {/* Mobile drawer */}
      {drawerOpen && (
        <>
          <div className="nav-drawer-scrim" onClick={() => setDrawerOpen(false)}/>
          <div className="nav-drawer" role="dialog" aria-label="Site navigation">
            <div className="nav-drawer-section">
              {[
                ['home', 'Home'],
                ['about', 'About'],
                ['services', 'Practice'],
                ['insights', 'Insights'],
                ['contact', 'Contact'],
              ].map(([id, label]) => (
                <a key={id} className={`nav-drawer-item ${page === id ? 'active' : ''}`}
                   onClick={() => go(id)}>{label}</a>
              ))}
            </div>
            {exploreSections.map(s => (
              <div key={s.title} className="nav-drawer-section">
                <div className="nav-drawer-title">{s.title}</div>
                {s.items.map(i => (
                  <a key={i.id} className={`nav-drawer-item ${page === i.id ? 'active' : ''}`}
                     onClick={() => go(i.id)}>
                    <span>{i.label}</span>
                    {i.sub && <span className="nav-drawer-sub">{i.sub}</span>}
                  </a>
                ))}
              </div>
            ))}
            <button className="nav-drawer-cta" onClick={() => go('intake')}>
              Begin a matter <span style={{ fontSize: 11 }}>→</span>
            </button>
          </div>
        </>
      )}
    </nav>
  );
};

const Footer = ({ onNav }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
            <BrandMark size={36} color="var(--paper)" accent="var(--gold)"/>
            <div className="brand-name" style={{ color: 'var(--paper)' }}>
              Tailored<em style={{ color: 'var(--slate-300)' }}>Mediation</em>
            </div>
          </div>
          <p style={{ color: 'var(--slate-300)', fontSize: 14, maxWidth: 340, lineHeight: 1.6 }}>
            Mediation, arbitration, special master, and forensic neutral services for technically complex disputes. Daniel B. Garrie, Esq. — founder, Law &amp; Forensics; adjunct, Harvard. Author of 20+ books and 300+ articles cited in 500+ opinions.
          </p>
        </div>
        <div>
          <h5>Practice</h5>
          <ul>
            <li><a onClick={() => onNav('mediation')}>Mediation</a></li>
            <li><a onClick={() => onNav('special-master')}>Special Master</a></li>
            <li><a onClick={() => onNav('forensic-neutral')}>Forensic Neutral</a></li>
            <li><a onClick={() => onNav('ai-disputes')}>AI Disputes</a></li>
            <li><a onClick={() => onNav('arbitration')}>Arbitration</a></li>
            <li><a onClick={() => onNav('process')}>Process &amp; Methodology</a></li>
            <li><a onClick={() => onNav('notable-matters')}>Notable Matters</a></li>
          </ul>
        </div>
        <div>
          <h5>Resources</h5>
          <ul>
            <li><a onClick={() => onNav('about')}>About Daniel Garrie</a></li>
            <li><a onClick={() => onNav('insights')}>Insights</a></li>
            <li><a onClick={() => onNav('publications')}>Publications &amp; Books</a></li>
            <li><a onClick={() => onNav('speaking')}>Speaking &amp; Events</a></li>
            <li><a onClick={() => onNav('faq')}>FAQ</a></li>
            <li><a onClick={() => onNav('engagement-terms')}>Engagement Terms</a></li>
          </ul>
        </div>
        <div>
          <h5>Reach</h5>
          <ul>
            <li><a onClick={() => onNav('intake')}>Match Intake</a></li>
            <li><a onClick={() => onNav('contact')}>Contact</a></li>
            <li>info@tailoredmediation.com</li>
            <li><strong style={{ color: 'var(--paper)' }}>Anchor venues:</strong> Los Angeles · New York · Tel Aviv · Geneva · Singapore</li>
            <li style={{ fontSize: 13, color: 'var(--slate-500)' }}>Additional in-person sessions in Seattle, Miami, Park City, Barcelona, Dubai, and Tokyo by arrangement.</li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Tailored Mediation · Daniel B. Garrie, Esq. · All rights reserved.</span>
        <span className="footer-legal-links">
          <a onClick={() => onNav('legal')} style={{ cursor: 'pointer' }}>Privacy</a>
          <span className="muted-sep">·</span>
          <a onClick={() => onNav('legal')} style={{ cursor: 'pointer' }}>Terms</a>
          <span className="muted-sep">·</span>
          <a onClick={() => onNav('legal')} style={{ cursor: 'pointer' }}>Disclaimer</a>
          <span className="muted-sep">·</span>
          <a onClick={() => onNav('legal')} style={{ cursor: 'pointer' }}>Accessibility</a>
        </span>
      </div>
    </div>
  </footer>
);

// HeroSchematic — refined orbital convergence diagram. Single dominant gesture.
// Two arcs sweep into a central gold node; subtle compass ring frames it.
const HeroSchematic = ({ variant = 'a' }) => (
  <svg viewBox="0 0 600 520" style={{ width: '100%', height: '100%', display: 'block' }}>
    <defs>
      <radialGradient id="hero-glow" cx="0.5" cy="0.5" r="0.5">
        <stop offset="0" stopColor="#D4B97A" stopOpacity="0.18"/>
        <stop offset="1" stopColor="#D4B97A" stopOpacity="0"/>
      </radialGradient>
    </defs>
    {/* central glow */}
    <circle cx="300" cy="260" r="200" fill="url(#hero-glow)"/>
    {/* compass rings */}
    {[210, 170, 130, 90].map((r, i) => (
      <circle key={i} cx="300" cy="260" r={r} fill="none"
        stroke="rgba(212,185,122,0.35)" strokeWidth="0.6"
        strokeDasharray={i % 2 ? '1 6' : ''}/>
    ))}
    {/* 12-tick compass marks on outer ring */}
    {Array.from({ length: 12 }).map((_, i) => {
      const a = (i * 30 - 90) * Math.PI / 180;
      const r1 = 218, r2 = (i % 3 === 0) ? 230 : 224;
      return (
        <line key={i}
          x1={300 + r1 * Math.cos(a)} y1={260 + r1 * Math.sin(a)}
          x2={300 + r2 * Math.cos(a)} y2={260 + r2 * Math.sin(a)}
          stroke="rgba(212,185,122,0.6)"
          strokeWidth={i % 3 === 0 ? 1 : 0.5}/>
      );
    })}
    {/* two converging arcs from opposite quadrants */}
    <path d="M 60 80 Q 220 120 280 240" fill="none"
      stroke="#D4B97A" strokeWidth="1.4" strokeOpacity="0.85" strokeLinecap="round"/>
    <path d="M 540 440 Q 380 400 320 280" fill="none"
      stroke="#D4B97A" strokeWidth="1.4" strokeOpacity="0.85" strokeLinecap="round" strokeDasharray="6 4"/>
    {/* origin nodes */}
    <circle cx="60"  cy="80"  r="6" fill="#D4B97A"/>
    <circle cx="540" cy="440" r="6" fill="#D4B97A"/>
    <circle cx="60"  cy="80"  r="14" fill="none" stroke="#D4B97A" strokeOpacity="0.4" strokeWidth="0.6"/>
    <circle cx="540" cy="440" r="14" fill="none" stroke="#D4B97A" strokeOpacity="0.4" strokeWidth="0.6"/>
    {/* convergence */}
    <circle cx="300" cy="260" r="16" fill="#D4B97A"/>
    <circle cx="300" cy="260" r="28" fill="none" stroke="#D4B97A" strokeOpacity="0.6" strokeWidth="1"/>
    {/* crosshair */}
    <line x1="300" y1="220" x2="300" y2="300" stroke="#D4B97A" strokeWidth="0.6"/>
    <line x1="260" y1="260" x2="340" y2="260" stroke="#D4B97A" strokeWidth="0.6"/>
    {/* mono labels — sparser */}
    <g fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#D4B97A" letterSpacing="0.18em">
      <text x="60"  y="60">PARTY · A</text>
      <text x="540" y="466" textAnchor="end">PARTY · B</text>
      <text x="300" y="200" textAnchor="middle" fillOpacity="0.85">RESOLUTION</text>
    </g>
    {/* subtle compass labels */}
    <g fontFamily="JetBrains Mono, monospace" fontSize="9" fill="rgba(212,185,122,0.5)" letterSpacing="0.2em">
      <text x="300" y="36"  textAnchor="middle">N</text>
      <text x="300" y="494" textAnchor="middle">S</text>
      <text x="60"  y="266" textAnchor="middle">W</text>
      <text x="540" y="266" textAnchor="middle">E</text>
    </g>
  </svg>
);

Object.assign(window, { BrandMark, Brand, Nav, Footer, HeroSchematic });
