/* Shared components: Nav, Footer, Modal, helpers */

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

// ===== Icons (minimal inline SVGs) =====
const Arrow = ({ size = 14 }) => (
  <svg className="arrow" width={size} height={size} viewBox="0 0 14 14" fill="none">
    <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);
const ArrowSmall = () => (
  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
    <path d="M2 6h8M7 3l3 3-3 3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);
const LinkedinIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
    <path d="M19 3A2 2 0 0121 5v14a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h14M8.34 18V10H5.67v8M7 8.84a1.54 1.54 0 100-3.08 1.54 1.54 0 000 3.08M18.34 18v-4.39c0-2.34-1.49-3.13-2.91-3.13a2.84 2.84 0 00-2.5 1.27V10h-2.69v8H12.93v-4.36a1.41 1.41 0 011.34-1.51c.74 0 1.41.37 1.41 1.49V18z"/>
  </svg>
);
const PhoneIcon = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
    <path d="M12.5 9.83v1.92a1.28 1.28 0 01-1.4 1.28A12.6 12.6 0 015.6 11.4a12.4 12.4 0 01-3.83-3.83A12.6 12.6 0 010 2.9a1.28 1.28 0 011.27-1.4h1.92a1.28 1.28 0 011.27 1.1c.08.62.23 1.23.44 1.81a1.28 1.28 0 01-.29 1.34l-.81.81a10.2 10.2 0 003.83 3.83l.81-.81a1.28 1.28 0 011.34-.29c.58.21 1.19.36 1.81.44a1.28 1.28 0 011.1 1.3z" stroke="currentColor" strokeWidth="1" fill="none"/>
  </svg>
);
const ChambersWordmark = () => (
  <svg viewBox="0 0 140 28" width="120" height="20">
    <text x="0" y="20" fontFamily="Cormorant Garamond, serif" fontWeight="500" fontSize="22" fill="currentColor" letterSpacing="0.02em">Chambers</text>
  </svg>
);

// ===== Logo (clean SVG, original — not the existing PNG mark) =====
const Logo = ({ light = false, compact = false }) => {
  const fg = light ? '#FBFAF5' : '#16161A';
  const accent = '#F2C744';
  if (compact) {
    return (
      <span className="nav-logo">
        <span className="nav-logo-mark" />
        <span style={{ color: fg }}>Horizons&Co</span>
      </span>
    );
  }
  return (
    <span className="nav-logo" style={{ color: fg }}>
      <span className="nav-logo-mark" />
      Horizons<span style={{ color: accent }}>&</span>Co
    </span>
  );
};

// ===== Locale toggle =====
const LocaleToggle = ({ locale, setLocale }) => (
  <div className="locale-toggle" role="group" aria-label="Language">
    {['EN', 'AR', 'RU', 'ZH'].map(L => (
      <button key={L} className={locale === L ? 'active' : ''} onClick={() => setLocale(L)}>{L}</button>
    ))}
  </div>
);

// ===== Nav =====
const Nav = ({ page, setPage, locale, setLocale, openConsult, t }) => {
  const links = [
    ['home', t('navHome', 'Home')],
    ['practices', t('navPractices', 'Practices')],
    ['experts', t('navExperts', 'Experts')],
    ['insights', t('navInsights', 'Insights')],
    ['about', t('navAbout', 'About')],
    ['contact', t('navContact', 'Contact')],
  ];
  return (
    <nav className="nav">
      <div className="wrap nav-row">
        <button onClick={() => setPage('home')} style={{ background: 'transparent', border: 0, padding: 0 }}>
          <Logo />
        </button>
        <div className="nav-links">
          {links.map(([key, label]) => (
            <button key={key} className={'nav-link' + (page === key || (key === 'practices' && page.startsWith && page.startsWith('practice/')) || (key === 'experts' && page.startsWith && page.startsWith('expert/')) ? ' active' : '')} onClick={() => setPage(key)}>
              {label}
            </button>
          ))}
        </div>
        <div className="nav-right">
          <LocaleToggle locale={locale} setLocale={setLocale} />
          <button className="btn btn-primary" onClick={openConsult}>
            {t('cta', 'Request consultation')} <Arrow />
          </button>
        </div>
      </div>
    </nav>
  );
};

// ===== Footer =====
const Footer = ({ setPage }) => (
  <footer className="footer">
    <div className="wrap">
      <div className="footer-grid">
        <div>
          <div className="brand">Horizons<span style={{ color: 'var(--saffron)' }}>&</span>Co</div>
          <p className="brand-blurb">Established 1999. An Emirati-founded, disputes-focused full-service UAE law firm. Dubai HQ + Abu Dhabi.</p>
          <div style={{ marginTop: 20, display: 'flex', gap: 12, alignItems: 'center' }}>
            <a href="https://www.linkedin.com/company/horizons-&-co-law-firm" target="_blank" rel="noreferrer" style={{ color: 'rgba(255,255,255,0.7)', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
              <LinkedinIcon /> LinkedIn
            </a>
          </div>
        </div>
        <div>
          <h5>Practices</h5>
          <ul>
            {PRACTICES.slice(0, 6).map(p => (
              <li key={p.id}><a onClick={() => setPage('practice/' + p.id)} style={{ cursor: 'pointer' }}>{p.title}</a></li>
            ))}
            <li><a onClick={() => setPage('practices')} style={{ cursor: 'pointer', color: 'var(--saffron)' }}>All practices →</a></li>
          </ul>
        </div>
        <div>
          <h5>Firm</h5>
          <ul>
            <li><a onClick={() => setPage('experts')} style={{ cursor: 'pointer' }}>Experts</a></li>
            <li><a onClick={() => setPage('insights')} style={{ cursor: 'pointer' }}>Insights</a></li>
            <li><a onClick={() => setPage('about')} style={{ cursor: 'pointer' }}>About</a></li>
            <li><a style={{ cursor: 'pointer' }}>Careers</a></li>
            <li><a onClick={() => setPage('contact')} style={{ cursor: 'pointer' }}>Contact</a></li>
          </ul>
        </div>
        <div>
          <h5>Offices</h5>
          <ul>
            <li><strong style={{ color: '#fff' }}>Dubai HQ</strong><br/><span style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)' }}>Burj Al Salam, SZR</span><br/><a href="tel:+97143544444">+971 4 354 4444</a></li>
            <li style={{ marginTop: 8 }}><strong style={{ color: '#fff' }}>Abu Dhabi</strong><br/><span style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)' }}>Al Jazira Towers, Suite 602</span><br/><a href="tel:+97126506333">+971 2 650 6333</a></li>
            <li style={{ marginTop: 8 }}><a href="mailto:info@horizlaw.ae" style={{ color: 'var(--saffron)' }}>info@horizlaw.ae</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <div>© 1999–2026 Horizons & Co Law Firm LLC. All rights reserved.</div>
        <div style={{ display: 'flex', gap: 24 }}>
          <a>Privacy</a>
          <a>Legal notices</a>
          <a>Site map</a>
        </div>
      </div>
    </div>
  </footer>
);

// ===== Consultation Modal =====
const ConsultModal = ({ open, onClose, prefill }) => {
  const [step, setStep] = useState('form');
  const [data, setData] = useState({ name: '', email: '', phone: '', practice: prefill?.practice || '', message: '' });

  useEffect(() => {
    if (open) { setStep('form'); setData(d => ({ ...d, practice: prefill?.practice || d.practice })); }
  }, [open, prefill]);

  useEffect(() => {
    const onKey = e => { if (e.key === 'Escape' && open) onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  const submit = e => {
    e.preventDefault();
    setStep('success');
  };

  return (
    <div className={'modal-overlay' + (open ? ' open' : '')} onClick={onClose}>
      <div className="modal" style={{ position: 'relative' }} onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.5"/></svg>
        </button>
        {step === 'form' ? <>
          <aside className="modal-aside">
            <div className="eyebrow eyebrow-light" style={{ color: 'var(--saffron)' }}>Confidential enquiry</div>
            <h2>Request a consultation.</h2>
            <p>An institutional enquiry channel. We will reply within one business day, in your preferred language, with the most appropriate partner for the matter.</p>
            <ul>
              <li>No fee disclosed</li>
              <li>Legal-privilege observed</li>
              <li>EN · AR · RU · ZH</li>
            </ul>
            <div style={{ marginTop: 28, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,0.12)', fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>
              For urgent matters: <a href="tel:+97143544444" style={{ color: '#fff' }}>+971 4 354 4444</a>
            </div>
          </aside>
          <form className="modal-body" onSubmit={submit}>
            <div className="field">
              <label>Full name</label>
              <input required value={data.name} onChange={e => setData({...data, name: e.target.value})} placeholder="Your full legal name"/>
            </div>
            <div className="field">
              <label>Email</label>
              <input type="email" required value={data.email} onChange={e => setData({...data, email: e.target.value})} placeholder="you@company.ae"/>
            </div>
            <div className="field">
              <label>Phone (optional)</label>
              <input value={data.phone} onChange={e => setData({...data, phone: e.target.value})} placeholder="+971 …"/>
            </div>
            <div className="field">
              <label>Practice area</label>
              <select value={data.practice} onChange={e => setData({...data, practice: e.target.value})}>
                <option value="">Select a practice…</option>
                {PRACTICES.map(p => <option key={p.id} value={p.id}>{p.title}</option>)}
                <option value="other">Other / unsure</option>
              </select>
            </div>
            <div className="field">
              <label>Brief description of the matter</label>
              <textarea rows={4} value={data.message} onChange={e => setData({...data, message: e.target.value})} placeholder="Please share enough context for us to route to the right partner. Privileged."/>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 8 }}>
              <button type="submit" className="btn btn-primary">Send enquiry <Arrow /></button>
              <span style={{ fontSize: 12, color: 'var(--muted)' }}>By submitting you agree to our privacy notice.</span>
            </div>
          </form>
        </> : (
          <div className="modal-success" style={{ gridColumn: '1 / -1' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--saffron)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
              <svg width="24" height="24" viewBox="0 0 24 24"><path d="M5 12l4 4 10-10" stroke="#16161A" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h2>Enquiry received.</h2>
            <p>Thank you, {data.name?.split(' ')[0] || 'we'}. Our team will reply within one business day with the most appropriate partner for {data.practice ? PRACTICES.find(p=>p.id===data.practice)?.title || 'your matter' : 'your matter'}.</p>
            <button className="btn btn-secondary" style={{ marginTop: 24 }} onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
};

// ===== Practice Card =====
const PracticeCard = ({ p, onClick, locale }) => (
  <article className={'practice-card' + (p.core ? ' is-core' : '')} onClick={onClick}>
    <span className="pc-num">{p.num}</span>
    <h3 className="pc-title">{locale === 'AR' ? p.ar : p.title}</h3>
    <p className="pc-sub">{p.blurb}</p>
    <span className="pc-arrow"><Arrow size={12}/></span>
  </article>
);

// ===== Expert Card =====
const ExpertCard = ({ e, onClick }) => (
  <article className="expert-card" onClick={onClick}>
    <div className="photo">
      {e.placeholder ? <PortraitPlaceholder name={e.name} /> : <img src={e.photo} alt={e.name}/>}
    </div>
    <div>
      <div className="name">{e.name}</div>
      <div className="role">{e.role}</div>
    </div>
  </article>
);

const PortraitPlaceholder = ({ name }) => {
  const initials = (name || '').split(/\s+/).filter(w => w[0] && /[A-Za-z]/.test(w[0])).slice(0, 2).map(w => w[0]).join('').toUpperCase();
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'repeating-linear-gradient(135deg, var(--paper-2) 0 18px, var(--stone) 18px 19px)', position: 'relative' }}>
      <div style={{ position: 'absolute', top: 12, left: 12, fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.1em', color: 'var(--muted)', textTransform: 'uppercase' }}>Awaiting portrait</div>
      <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 64, color: 'var(--ink)', opacity: 0.55 }}>{initials}</div>
    </div>
  );
};

// ===== Insight Card =====
const InsightCard = ({ i, small, onClick }) => (
  <article className={'insight-card' + (small ? ' small' : '')} onClick={onClick}>
    <div className="img"><img src={i.image} alt=""/></div>
    <div className="cat">{i.cat}</div>
    <h4 className="title serif">{i.title}</h4>
    <div className="date">{i.date} · {i.practice}</div>
  </article>
);

// ===== Section Head =====
const SectionHead = ({ eyebrow, title, lede, action }) => (
  <header className="section-head">
    <div>
      <span className="eyebrow">{eyebrow}</span>
      <h2 className="serif-tight">{title}</h2>
    </div>
    <div>
      {lede ? <p className="lede">{lede}</p> : null}
      {action ? <div style={{ marginTop: 16 }}>{action}</div> : null}
    </div>
  </header>
);

// ===== Award card =====
const AwardCard = ({ a }) => (
  <div className={'award' + (a.dark ? ' dark' : '')}>
    <span className="yr">{a.yr}</span>
    <span className="issuer">{a.issuer}</span>
    <div className="band serif">{a.band}</div>
    <div className="cat">{a.cat}</div>
  </div>
);

// ===== Map plate (stylised, no real coords — brief says don't guess) =====
const MapPlate = ({ city }) => (
  <div className="map-plate" aria-label={city + ' office location'}>
    <svg viewBox="0 0 220 180" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <pattern id={`grid-${city}`} width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M 20 0 L 0 0 0 20" fill="none" stroke="rgba(0,0,0,0.06)" strokeWidth="0.5"/>
        </pattern>
      </defs>
      <rect width="220" height="180" fill={`url(#grid-${city})`} />
      {/* abstracted street lines */}
      <path d="M0 70 Q60 60 110 80 T220 90" stroke="var(--line-2)" strokeWidth="2" fill="none"/>
      <path d="M0 110 Q70 130 130 110 T220 120" stroke="var(--line-2)" strokeWidth="1.5" fill="none" opacity="0.7"/>
      <path d="M70 0 Q90 60 110 100 T130 180" stroke="var(--line-2)" strokeWidth="1.5" fill="none" opacity="0.6"/>
      {/* pin */}
      <g transform="translate(110,90)">
        <circle r="20" fill="var(--saffron)" opacity="0.25"/>
        <circle r="6" fill="var(--ink)"/>
        <circle r="2" fill="var(--saffron)"/>
      </g>
      <text x="110" y="135" fontSize="9" fontFamily="JetBrains Mono, monospace" textAnchor="middle" fill="var(--muted)" letterSpacing="0.15em">{city.toUpperCase()}</text>
      <text x="110" y="148" fontSize="7" fontFamily="JetBrains Mono, monospace" textAnchor="middle" fill="var(--muted)">coordinates to confirm</text>
    </svg>
  </div>
);

// Translation helper (very small dictionary)
const makeT = (locale) => (key, fallback) => {
  if (locale === 'AR' && AR[key]) return AR[key];
  return fallback;
};

Object.assign(window, {
  Arrow, ArrowSmall, LinkedinIcon, PhoneIcon, ChambersWordmark,
  Logo, LocaleToggle, Nav, Footer, ConsultModal,
  PracticeCard, ExpertCard, PortraitPlaceholder, InsightCard, SectionHead,
  AwardCard, MapPlate, makeT,
});
