// ============================================================
// Shared UI components — masthead, footer, cards, icons
// ============================================================

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

// ---------- Icons (inline SVG) ----------
const Icon = {
  whatsapp: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1l-.9 1.1c-.2.2-.4.3-.7.1-.3-.1-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.4.1-.6.1-.1.2-.3.4-.5l.3-.4c.1-.2 0-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1.1 1-1.1 2.5s1.1 2.9 1.3 3.1c.1.2 2.2 3.4 5.3 4.7.7.3 1.3.5 1.8.6.7.2 1.4.2 2 .1.6-.1 1.7-.7 2-1.4.2-.7.2-1.3.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 4.9L2 22l5.3-1.4c1.4.7 2.9 1.1 4.5 1.1 5.5 0 10-4.5 10-10s-4.5-10-9.8-10c-.1 0 0 0 0 0z" />
    </svg>
  ),
  search: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" />
    </svg>
  ),
  arrow: (p) => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  ),
  x: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
    </svg>
  ),
  linkedin: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M19 0h-14C2.24 0 0 2.24 0 5v14c0 2.76 2.24 5 5 5h14c2.76 0 5-2.24 5-5V5c0-2.76-2.24-5-5-5zM8 19H5V8h3v11zM6.5 6.73c-.97 0-1.75-.79-1.75-1.75S5.53 3.23 6.5 3.23s1.75.79 1.75 1.75-.78 1.75-1.75 1.75zM20 19h-3v-5.6c0-3.37-4-3.11-4 0V19h-3V8h3v1.76c1.4-2.58 7-2.77 7 2.47V19z"/>
    </svg>
  ),
  link: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.72M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.72-1.72"/>
    </svg>
  ),
  edit: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M12 20h9M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4z"/>
    </svg>
  ),
  trash: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/>
    </svg>
  ),
  eye: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z"/><circle cx="12" cy="12" r="3"/>
    </svg>
  ),
  plus: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M12 5v14M5 12h14"/>
    </svg>
  ),
  upload: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/>
    </svg>
  ),
  check: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" {...p}>
      <path d="M20 6 9 17l-5-5"/>
    </svg>
  ),
  eyeOff: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><path d="M1 1l22 22"/>
    </svg>
  ),
  alert: (p) => (
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/>
    </svg>
  ),
  image: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/>
    </svg>
  ),
  download: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/>
    </svg>
  ),
};

// ---------- Brand monogram (logo) ----------
function Monogram({ size = 48 }) {
  return (
    <svg width={size} height={size * 0.35} viewBox="0 0 120 42" fill="none">
      <path
        d="M10 30 Q 25 8 45 24 T 75 24 T 110 14"
        stroke="#A8821C" strokeWidth="2.2" fill="none" strokeLinecap="round"
      />
      <path
        d="M10 30 Q 25 8 45 24 T 75 24 T 110 14"
        stroke="#C9A23A" strokeWidth="0.8" fill="none" strokeLinecap="round"
        transform="translate(0,3)" opacity="0.6"
      />
    </svg>
  );
}

// ---------- Masthead ----------
function Masthead({ active = 'home', onNav, categories }) {
  const today = new Date();
  const dias = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];
  const meses = ['JAN', 'FEV', 'MAR', 'ABR', 'MAI', 'JUN', 'JUL', 'AGO', 'SET', 'OUT', 'NOV', 'DEZ'];
  const dateStr = `${dias[today.getDay()]}, ${today.getDate()} DE ${meses[today.getMonth()]} DE ${today.getFullYear()}`;

  return (
    <header className="masthead">
      <div className="masthead-top">
        <div className="left">
          <span>{dateStr}</span>
          <span>EDIÇÃO BRASIL</span>
          <span>Nº 247</span>
        </div>
        <div className="center">Santos · São Paulo</div>
        <div className="right">
          <a href="/" className="back-to-site">← Site Institucional</a>
          <a href="#/admin">Acesso Editorial</a>
          <a className="masthead-cta" href="https://wa.me/5513978002785" target="_blank" rel="noopener">
            <Icon.whatsapp /> (13) 97800-2785
          </a>
        </div>
      </div>

      <div className="masthead-banner">
        <div className="container-wide ed-meta">
          <span>Vol. XII · Edição diária</span>
          <span>Crônicas de Defesa</span>
          <span>OAB-SP 377.580</span>
        </div>
        <h1 className="masthead-logo">
          <a href="#/" aria-label="Angelo Santos Advogados">
            <img src="src/logo.png" alt="Angelo Santos Advogados" />
          </a>
        </h1>
        <span className="tagline">Crônicas, ensaios e análises do Direito Penal brasileiro</span>
        <div className="ornament" aria-hidden="true" />
      </div>

      <nav className="masthead-nav">
        <a href="#/" className={active === 'home' ? 'active' : ''}>Capa</a>
        {(categories || []).map(c => (
          <a key={c.id}
             href={`#/categoria/${c.slug}`}
             className={active === c.slug ? 'active' : ''}>
            {c.name}
          </a>
        ))}
        <a href="#/sobre">Sobre o Autor</a>
        <a href="#/contato">Contato</a>
      </nav>
    </header>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="foot">
      <div className="container">
        <div className="top">
          <div>
            <h1 className="brand">Angelo Santos</h1>
            <p className="tag">Crônicas, ensaios e análises do<br />Direito Penal brasileiro.</p>
            <p style={{ marginTop: 18, fontSize: 13, color: '#aaa392' }}>
              ANGELO SANTOS ADVOCACIA<br />
              OAB-SP 377.580 · CNPJ 47.581.64/0001-61
            </p>
          </div>
          <div>
            <h5>Editorial</h5>
            <ul>
              <li><a href="#/">Capa</a></li>
              <li><a href="#/categoria/tribuna">Tribuna do Júri</a></li>
              <li><a href="#/categoria/maria-penha">Maria da Penha</a></li>
              <li><a href="#/categoria/estelionato">Estelionato &amp; Golpes</a></li>
              <li><a href="#/categoria/trafico">Tráfico &amp; Drogas</a></li>
              <li><a href="#/categoria/habeas">Habeas Corpus</a></li>
              <li><a href="#/categoria/opiniao">Opinião</a></li>
            </ul>
          </div>
          <div>
            <h5>Escritório</h5>
            <ul>
              <li>Rua São Paulo, nº 41, sala 502</li>
              <li>Vila Belmiro, Santos – SP</li>
              <li>Seg-Sex 9:00 – 19:00</li>
              <li><strong style={{ color: '#fff' }}>(13) 97800-2785</strong></li>
            </ul>
          </div>
          <div>
            <h5>Acesso</h5>
            <ul>
              <li><a href="#/admin">Login editorial</a></li>
              <li><a href="https://wa.me/5513978002785">WhatsApp do escritório</a></li>
              <li><a href="#/">Política de privacidade</a></li>
              <li><a href="#/">Termos de uso</a></li>
            </ul>
          </div>
        </div>
        <div className="bottom">
          <span>© {new Date().getFullYear()} ANGELO SANTOS ADVOCACIA · TODOS OS DIREITOS RESERVADOS</span>
          <span>FEITO COM RIGOR EM SANTOS, SP</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- Article card ----------
function ArticleCard({ article, size = 'md' }) {
  if (!article) return null;
  const cat = categoryById(article.category);
  const cls = size === 'sm' ? 'card card-sm' : size === 'lg' ? 'card card-lg' : 'card';
  return (
    <a href={`#/artigo/${article.slug}`} className={cls}>
      {article.cover && (
        <div className="img"><img src={article.cover} alt="" loading="lazy" /></div>
      )}
      {cat && <span className="eyebrow">{cat.name}</span>}
      <h3>{article.title}</h3>
      {size !== 'sm' && article.subtitle && <p className="dek">{article.subtitle}</p>}
      <div className="meta">
        <span>{fmtDate(article.publishedAt)}</span>
        <span>·</span>
        <span>{readingTime(article.body)} min de leitura</span>
      </div>
    </a>
  );
}

// ---------- Toast ----------
function Toast({ message, onDone }) {
  useEffect(() => {
    if (!message) return;
    const t = setTimeout(onDone, 2200);
    return () => clearTimeout(t);
  }, [message, onDone]);
  if (!message) return null;
  return <div className="toast">{message}</div>;
}

// ---------- Hash router hook ----------
function useHashRoute() {
  const [hash, setHash] = useState(() => window.location.hash || '#/');
  useEffect(() => {
    const onHash = () => { setHash(window.location.hash || '#/'); window.scrollTo({ top: 0, behavior: 'instant' }); };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // parse
  const path = hash.replace(/^#\/?/, '/').replace(/\/+$/, '') || '/';
  const parts = path.split('/').filter(Boolean);
  return { hash, path, parts, navigate: (h) => { window.location.hash = h; } };
}

Object.assign(window, { Icon, Monogram, Masthead, Footer, ArticleCard, Toast, useHashRoute });
