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

/* ============================================================
   Shared atoms / decorative motifs
   ============================================================ */

function Icon({ name, size = 18, strokeWidth = 1.5, style }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = '';
      const el = document.createElement('i');
      el.setAttribute('data-lucide', name);
      el.style.width = size + 'px';
      el.style.height = size + 'px';
      ref.current.appendChild(el);
      window.lucide.createIcons({
        attrs: { 'stroke-width': strokeWidth, width: size, height: size }
      });
    }
  }, [name, size, strokeWidth]);
  return <span ref={ref} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', ...style }} />;
}

function Logo({ size = 28, color = 'currentColor', showTag = true, dark = true }) {
  // Both logo files are black; on dark surfaces we invert to bright
  const filter = dark ? 'brightness(0) invert(1)' : 'none';
  const markSize = size * 1.2;
  // Wordmark SVG aspect ratio is 463:94 ≈ 4.93:1
  const wordmarkH = size * 0.95;
  const wordmarkW = wordmarkH * (463 / 94);
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', color, gap: 0 }}>
      <img src="assets/logo-mark.png" alt="" width={markSize} height={markSize}
        style={{ filter, display: 'block', marginRight: size * 0.36 }} />
      <img src="assets/logo-wordmark.svg" alt="adim"
        width={wordmarkW} height={wordmarkH}
        style={{ filter, display: 'block' }} />
      {showTag && (
        <span style={{ display: 'inline-flex', alignItems: 'center', marginLeft: 14, gap: 10 }}>
          <span style={{ width: 1, height: size * 0.75, background: 'currentColor', opacity: 0.20 }} />
          <span style={{
            fontFamily: 'var(--font-mono)',
            fontSize: 10,
            letterSpacing: '0.16em',
            textTransform: 'uppercase',
            opacity: 0.55,
            color,
          }}>AI studio</span>
        </span>
      )}
    </div>
  );
}

function LogoMark({ size = 40, dark = true }) {
  const filter = dark ? 'brightness(0) invert(1)' : 'none';
  return (
    <img src="assets/logo-mark.png" alt="adim" width={size} height={size}
      style={{ filter, display: 'block' }} />
  );
}

/* Registration mark — small blueprint cross */
function RegMark({ size = 10, color = 'var(--text-dim)' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 10 10" style={{ display: 'block', flexShrink: 0 }}>
      <line x1="0" y1="5" x2="10" y2="5" stroke={color} strokeWidth="1" />
      <line x1="5" y1="0" x2="5" y2="10" stroke={color} strokeWidth="1" />
      <circle cx="5" cy="5" r="1.5" fill="none" stroke={color} strokeWidth="0.75" />
    </svg>
  );
}

/* Corner brackets — used on featured cards / sections */
function CornerBrackets({ inset = 0, color = 'var(--accent)', size = 12, strokeWidth = 1 }) {
  const positions = [
    { top: inset, left: inset, rotate: 0 },
    { top: inset, right: inset, rotate: 90 },
    { bottom: inset, right: inset, rotate: 180 },
    { bottom: inset, left: inset, rotate: 270 },
  ];
  return (
    <>
      {positions.map((p, i) => (
        <svg key={i} width={size} height={size} viewBox="0 0 12 12"
          style={{ position: 'absolute', pointerEvents: 'none', transform: `rotate(${p.rotate}deg)`,
            top: p.top, left: p.left, right: p.right, bottom: p.bottom }}>
          <path d="M 0 5 L 0 0 L 5 0" stroke={color} strokeWidth={strokeWidth} fill="none" />
        </svg>
      ))}
    </>
  );
}

/* Schematic grid background — repeating dot or line grid */
function GridBackground({ kind = 'dot', opacity = 0.15 }) {
  const bg = kind === 'dot'
    ? `radial-gradient(circle, rgba(255,255,255,${opacity * 0.5}) 1px, transparent 1px)`
    : `linear-gradient(rgba(255,255,255,${opacity * 0.3}) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,${opacity * 0.3}) 1px, transparent 1px)`;
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      backgroundImage: bg,
      backgroundSize: kind === 'dot' ? '24px 24px' : '48px 48px',
      maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 80%)',
    }} />
  );
}

/* Nav bar — used at the top of each page artboard */
function Nav({ light = false, current = '' }) {
  const items = [
    { id: 'products', label: 'Products' },
    { id: 'services', label: 'Services' },
    { id: 'privacy',  label: 'Privacy' },
    { id: 'about',    label: 'About' },
  ];
  return (
    <nav className={light ? 'ad-on-light' : ''} style={{
      height: 64,
      padding: '0 40px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      borderBottom: `1px solid ${light ? 'rgba(11,13,16,0.08)' : 'var(--hairline)'}`,
      background: light ? 'var(--bone)' : 'var(--obsidian)',
      position: 'relative',
    }}>
      <Logo size={22} color={light ? 'var(--ink)' : 'var(--text-bright)'} dark={!light} />
      <div className="ad-nav-items" style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
        {items.map(it => (
          <a key={it.id} href="#" style={{
            color: light ? 'var(--ink-soft)' : (current === it.id ? 'var(--text-bright)' : 'var(--text-mute)'),
            fontSize: 14, fontWeight: 500, textDecoration: 'none',
            borderBottom: 'none',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            {current === it.id && (
              <span style={{ width: 4, height: 4, borderRadius: 99, background: 'var(--accent)' }} />
            )}
            {it.label}
          </a>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span className="ad-micro ad-nav-meta" style={{ color: light ? 'var(--ink-mute)' : 'var(--text-dim)' }}>
          Vilnius · LT
        </span>
        <a href="#" className="ad-btn ad-btn-sm ad-btn-accent" style={{ textDecoration: 'none' }}>
          Start a project
        </a>
      </div>
    </nav>
  );
}

/* Footer */
function Footer() {
  const cols = [
    { title: 'Studio', items: ['Products', 'Services', 'Privacy', 'About'] },
    { title: 'Products', items: ['Adim Lex'] },
    { title: 'Contact', items: ['hello@adim.ai', 'Vilnius, Lithuania'] },
  ];
  return (
    <footer style={{
      background: 'var(--obsidian-rich)',
      padding: '80px 40px 32px',
      borderTop: '1px solid var(--hairline)',
    }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div className="ad-stack-2" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 48, marginBottom: 72 }}>
          <div>
            <Logo size={26} color="var(--text-bright)" />
            <p style={{ marginTop: 24, color: 'var(--text-mute)', fontSize: 14, maxWidth: 320 }}>
              An AI studio building quiet, private, audited AI for serious businesses
              — law firms, finance, healthcare, regulated industries.
            </p>
          </div>
          {cols.map(col => (
            <div key={col.title}>
              <div className="ad-micro" style={{ color: 'var(--text-dim)', marginBottom: 16 }}>{col.title}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {col.items.map(it => (
                  <li key={it}>
                    <a href="#" style={{ color: 'var(--text)', fontSize: 14, borderBottom: 'none' }}>{it}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ height: 1, background: 'var(--hairline)', marginBottom: 24 }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <RegMark />
            <span className="ad-micro" style={{ color: 'var(--text-dim)' }}>
              © 2026 ADIM
            </span>
          </div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="#" style={{ color: 'var(--text-mute)', fontSize: 12, borderBottom: 'none' }}>Privacy</a>
            <a href="#" style={{ color: 'var(--text-mute)', fontSize: 12, borderBottom: 'none' }}>Terms</a>
            <a href="#" style={{ color: 'var(--text-mute)', fontSize: 12, borderBottom: 'none' }}>GitHub</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* Tiny diagram primitive — connection node */
function Node({ x, y, w = 120, h = 36, label, accent = false, mono = false, mark }) {
  return (
    <g transform={`translate(${x}, ${y})`}>
      <rect width={w} height={h} rx="3"
        fill={accent ? 'var(--accent-soft)' : 'var(--carbon)'}
        stroke={accent ? 'var(--accent)' : 'var(--hairline-strong)'}
        strokeWidth="1" />
      {mark && (
        <circle cx="10" cy={h / 2} r="3" fill={accent ? 'var(--accent)' : 'var(--text-mute)'} />
      )}
      <text x={mark ? 22 : 12} y={h / 2 + 4} fontSize="11"
        fontFamily={mono ? 'var(--font-mono)' : 'var(--font-ui)'}
        fontWeight="500"
        letterSpacing={mono ? '0.04em' : '0'}
        fill={accent ? 'var(--accent)' : 'var(--text-bright)'}>
        {label}
      </text>
    </g>
  );
}

function Connector({ from, to, dashed = false, label }) {
  const path = `M ${from.x} ${from.y} L ${(from.x + to.x) / 2} ${from.y} L ${(from.x + to.x) / 2} ${to.y} L ${to.x} ${to.y}`;
  return (
    <g>
      <path d={path} stroke="var(--hairline-strong)" strokeWidth="1" fill="none"
        strokeDasharray={dashed ? '3 3' : 'none'} />
      <circle cx={to.x} cy={to.y} r="2" fill="var(--text-mute)" />
      {label && (
        <text x={(from.x + to.x) / 2 + 6} y={(from.y + to.y) / 2 + 4} fontSize="10"
          fontFamily="var(--font-mono)" letterSpacing="0.08em" fill="var(--text-dim)">
          {label}
        </text>
      )}
    </g>
  );
}

/* Numbered label — e.g. "01/" used in editorial layouts */
function NumLabel({ n, total }) {
  return (
    <div className="ad-num" style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <span style={{ color: 'var(--accent)' }}>{String(n).padStart(2, '0')}</span>
      <span>/</span>
      <span>{String(total).padStart(2, '0')}</span>
    </div>
  );
}

Object.assign(window, {
  Icon, Logo, LogoMark, RegMark, CornerBrackets, GridBackground,
  Nav, Footer, Node, Connector, NumLabel,
});
