
const { useState, useEffect } = React;

const CornerBracket = ({ children, style = {}, color, padding = 16 }) => {
  const c = color || 'var(--accent)';
  return (
    <div style={{ position: 'relative', padding: padding, ...style }}>
      <div style={{ position:'absolute', top:0, left:0, width:12, height:12,
        borderTop:`1px solid ${c}`, borderLeft:`1px solid ${c}`, pointerEvents:'none' }} />
      <div style={{ position:'absolute', top:0, right:0, width:12, height:12,
        borderTop:`1px solid ${c}`, borderRight:`1px solid ${c}`, pointerEvents:'none' }} />
      <div style={{ position:'absolute', bottom:0, left:0, width:12, height:12,
        borderBottom:`1px solid ${c}`, borderLeft:`1px solid ${c}`, pointerEvents:'none' }} />
      <div style={{ position:'absolute', bottom:0, right:0, width:12, height:12,
        borderBottom:`1px solid ${c}`, borderRight:`1px solid ${c}`, pointerEvents:'none' }} />
      {children}
    </div>
  );
};

const StatusBadge = ({ status }) => {
  const configs = {
    'in-progress': { label: 'IN PROGRESS',  color: 'var(--warning)', pulse: true  },
    'completed':   { label: 'COMPLETED',    color: 'var(--success)', pulse: false },
    'classified':  { label: 'CLASSIFIED',   color: 'var(--danger)',  pulse: false },
    'placeholder': { label: 'PLACEHOLDER',  color: 'var(--muted)',   pulse: false },
  };
  const cfg = configs[status] || configs['placeholder'];
  return (
    <div style={{ display:'flex', alignItems:'center', gap:7 }}>
      <div style={{
        width:6, height:6, borderRadius:'50%',
        background: cfg.color,
        boxShadow: `0 0 8px ${cfg.color}88`,
        animation: cfg.pulse ? 'hudPulse 2s ease-in-out infinite' : 'none',
        flexShrink: 0,
      }} />
      <span style={{
        fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.14em',
        color: cfg.color, padding:'2px 7px',
        border:`1px solid ${cfg.color}44`,
        background:`${cfg.color}12`,
      }}>
        {cfg.label}
      </span>
    </div>
  );
};

const SectionLabel = ({ label, index }) => (
  <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
    <span style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--muted)', letterSpacing:'0.18em', flexShrink:0 }}>
      {String(index).padStart(2,'0')}
    </span>
    <div style={{ width:24, height:1, background:'var(--border)' }} />
    <span style={{ fontFamily:'var(--mono)', fontSize:11.5, color:'var(--accent)', letterSpacing:'0.16em', fontWeight:500 }}>
      {label}
    </span>
    <div style={{ flex:1, height:1, background:'var(--border)' }} />
  </div>
);

const HRule = ({ accent = false }) => (
  <div style={{
    height:1,
    background: accent
      ? 'linear-gradient(to right, var(--accent), var(--border) 70%, transparent)'
      : 'var(--border)',
    margin:'0',
  }} />
);

const MonoLabel = ({ children, dim = false }) => (
  <span style={{
    fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em',
    color: dim ? 'var(--muted)' : 'var(--text-sec)',
    textTransform:'uppercase',
  }}>
    {children}
  </span>
);

const PlaceholderBlock = ({ text }) => {
  const clean = (text || '').replace(/^\/\/\s*/, '');
  return (
    <div style={{
      fontFamily:'var(--sans-body)', fontStyle:'italic',
      fontSize:14.5, color:'var(--text-sec)',
      lineHeight:1.7, padding:'14px 16px',
      background:'var(--accent-glow)',
      border:'1px dashed var(--border-bright)',
      borderLeft:'2px solid var(--accent-dim)',
      flex: 1, maxWidth: '64ch',
    }}>
      {clean}
    </div>
  );
};

const formatField = (v) => {
  if (v == null || v === '') return { text: '', placeholder: false };
  if (v.startsWith('//')) return { text: v.replace(/^\/\/\s*/, ''), placeholder: true };
  return { text: v, placeholder: false };
};

const Tag = ({ label }) => {
  const isHolder = label && label.startsWith('//');
  const clean = isHolder ? label.replace(/^\/\/\s*/, '') : label;
  return (
    <span style={{
      fontFamily: 'var(--mono)', fontSize: 11.5, letterSpacing: '0.1em',
      padding: '4px 10px',
      border: `1px ${isHolder ? 'dashed' : 'solid'} ${isHolder ? 'var(--border)' : 'var(--border-bright)'}`,
      color: isHolder ? 'var(--muted)' : 'var(--text-pri)',
      background: isHolder ? 'transparent' : 'var(--surface)',
      fontStyle: isHolder ? 'italic' : 'normal',
      display: 'inline-flex', alignItems: 'center',
      whiteSpace: 'nowrap',
    }}>
      {clean}
    </span>
  );
};

const OrbitalDiagram = ({ size = 340, opacity = 0.25 }) => (
  <svg width={size} height={size} viewBox="0 0 340 340" fill="none"
    style={{ pointerEvents:'none', opacity }}>
    <circle cx="170" cy="170" r="6" fill="var(--accent)" opacity="0.9" />
    <circle cx="170" cy="170" r="12" fill="none" stroke="var(--accent)" strokeWidth="0.5" opacity="0.4" />
    <ellipse cx="170" cy="170" rx="55"  ry="55"  stroke="var(--accent)" strokeWidth="0.6" />
    <ellipse cx="170" cy="170" rx="95"  ry="52"  stroke="var(--accent)" strokeWidth="0.5"
      transform="rotate(28 170 170)" />
    <ellipse cx="170" cy="170" rx="135" ry="38"  stroke="var(--accent)" strokeWidth="0.4"
      transform="rotate(75 170 170)" />
    <ellipse cx="170" cy="170" rx="155" ry="70"  stroke="var(--accent)" strokeWidth="0.3"
      transform="rotate(-20 170 170)" />
    <circle cx="225" cy="170" r="3" fill="var(--accent)" opacity="0.8" />
    <circle cx="132" cy="118" r="2.5" fill="var(--accent)" opacity="0.7" />
    <circle cx="160" cy="35"  r="2" fill="var(--accent)" opacity="0.6" />
    <circle cx="308" cy="185" r="2" fill="var(--accent)" opacity="0.5" />
    <line x1="170" y1="155" x2="170" y2="165" stroke="var(--accent)" strokeWidth="0.5" />
    <line x1="155" y1="170" x2="165" y2="170" stroke="var(--accent)" strokeWidth="0.5" />
    <path d="M10 30 L10 10 L30 10" stroke="var(--accent)" strokeWidth="0.8" opacity="0.5" />
    <path d="M330 30 L330 10 L310 10" stroke="var(--accent)" strokeWidth="0.8" opacity="0.5" />
    <path d="M10 310 L10 330 L30 330" stroke="var(--accent)" strokeWidth="0.8" opacity="0.5" />
    <path d="M330 310 L330 330 L310 330" stroke="var(--accent)" strokeWidth="0.8" opacity="0.5" />
    <line x1="170" y1="0" x2="170" y2="340" stroke="var(--accent)" strokeWidth="0.2" opacity="0.3" strokeDasharray="3 8" />
    <line x1="0" y1="170" x2="340" y2="170" stroke="var(--accent)" strokeWidth="0.2" opacity="0.3" strokeDasharray="3 8" />
  </svg>
);

Object.assign(window, {
  CornerBracket, StatusBadge, SectionLabel, HRule,
  MonoLabel, PlaceholderBlock, Tag, OrbitalDiagram,
  formatField,
});

const Chip = ({ label, sublabel, sys, size = 'md', variant = 'default', onClick, href, children, style = {}, target, rel, ...rest }) => {
  const sized = {
    sm: { fontSize: 11.5, padding: '4px 10px', sysSize: 9,  subSize: 9,  gap: 7 },
    md: { fontSize: 12,   padding: '7px 14px', sysSize: 9,  subSize: 9,  gap: 8 },
    lg: { fontSize: 14,   padding: '9px 18px', sysSize: 10, subSize: 10, gap: 8 },
  }[size] || { fontSize: 12, padding: '7px 14px', sysSize: 9, subSize: 9, gap: 8 };

  const v = {
    default:     { color: 'var(--text-pri)', bg: 'var(--surface)',     border: 'var(--border-bright)', weight: 500, dashed: false },
    active:      { color: 'var(--bg)',       bg: 'var(--accent)',      border: 'var(--accent)',        weight: 600, dashed: false },
    dim:         { color: 'var(--muted)',    bg: 'transparent',        border: 'var(--border)',        weight: 400, dashed: false },
    placeholder: { color: 'var(--muted)',    bg: 'transparent',        border: 'var(--border)',        weight: 400, dashed: true  },
  }[variant] || {};

  const Inner = href ? 'a' : (onClick ? 'button' : 'span');

  return (
    <Inner
      href={href}
      target={target}
      rel={rel}
      onClick={onClick}
      style={{
        fontFamily: 'var(--mono)', fontSize: sized.fontSize, letterSpacing: '0.1em',
        padding: sized.padding,
        border: `1px ${v.dashed ? 'dashed' : 'solid'} ${v.border}`,
        color: v.color, background: v.bg,
        cursor: (onClick || href) ? 'pointer' : 'default',
        whiteSpace: 'nowrap',
        transition: 'all 0.15s', fontWeight: v.weight,
        textDecoration: 'none',
        display: 'inline-flex', alignItems: 'center', gap: sized.gap,
        fontStyle: variant === 'placeholder' ? 'italic' : 'normal',
        ...style,
      }}
      onMouseEnter={e => {
        if (variant !== 'active' && (onClick || href)) {
          e.currentTarget.style.borderColor = 'var(--accent)';
          e.currentTarget.style.color = 'var(--accent)';
        }
      }}
      onMouseLeave={e => {
        if (variant !== 'active' && (onClick || href)) {
          e.currentTarget.style.borderColor = v.border;
          e.currentTarget.style.color = v.color;
        }
      }}
      {...rest}
    >
      {sys && <span style={{ fontSize: sized.sysSize, opacity: 0.7, letterSpacing: '0.14em' }}>{sys}</span>}
      {label && <span>{label}</span>}
      {sublabel && <span style={{ fontSize: sized.subSize, opacity: 0.6 }}>{sublabel}</span>}
      {children}
    </Inner>
  );
};

Object.assign(window, { Chip });

const SiteNav = ({ sys, name, children, tall }) => {
  const data = window.PORTFOLIO_DATA;
  const [open, setOpen] = useState(false);
  const [backHover, setBackHover] = useState(false);
  const [menuHover, setMenuHover] = useState(false);

  useEffect(() => {
    if (!open) return;
    const onKey = e => e.key === 'Escape' && setOpen(false);
    const onClick = e => {
      if (!e.target.closest || !e.target.closest('.sitenav-menu-root')) setOpen(false);
    };
    document.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onClick);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onClick);
    };
  }, [open]);

  const items = [
    { href: 'Main_Home.html',           sys: 'SYS.001', label: 'PORTFOLIO' },
    { href: 'About.html',               sys: 'SYS.002', label: 'ABOUT' },
    { href: 'Skills.html',              sys: 'SYS.003', label: 'SKILLS' },
    ...((data && data.projects) || []).map((p, i) => ({
      href:  `Project.html#${p.id}`,
      sys:   `SYS.${String(i + 4).padStart(3, '0')}`,
      label: `${p.id} · ${p.short || p.title}`,
    })),
  ];

  const H  = tall ? 72 : 44;
  const FS = tall ? 13 : 10;

  const cell = {
    padding: '0 16px', height: '100%',
    display: 'flex', alignItems: 'center', gap: 8,
    fontFamily: 'var(--mono)', fontSize: FS, letterSpacing: '0.14em',
    borderRight: '1px solid var(--border)',
    whiteSpace: 'nowrap',
  };

  return (
    <div className={`page-nav top-bar${tall ? ' sitenav-tall' : ''}`} style={{
      display: 'flex', alignItems: 'stretch', height: H, flexShrink: 0,
      backgroundColor: 'var(--bg-2)', borderBottom: '1px solid var(--border)',
      position: 'relative',
    }}>
      <a href="Main_Home.html"
        onMouseEnter={() => setBackHover(true)}
        onMouseLeave={() => setBackHover(false)}
        style={{
          ...cell,
          color: backHover ? 'var(--accent)' : 'var(--text-sec)',
          textDecoration: 'none', transition: 'color 0.15s',
        }}
      >← BACK</a>

      <div className="sitenav-brand" style={{ ...cell, color: 'var(--muted)' }}>BRIAN WITANOWSKI</div>

      <div className="sitenav-menu-root" style={{ position: 'relative', display: 'flex' }}>
        <button
          onClick={() => setOpen(o => !o)}
          onMouseEnter={() => setMenuHover(true)}
          onMouseLeave={() => setMenuHover(false)}
          style={{
            ...cell,
            background: open ? 'var(--surface-2)' : 'transparent',
            border: 'none', borderRight: '1px solid var(--border)',
            color: open || menuHover ? 'var(--accent)' : 'var(--text-sec)',
            cursor: 'pointer', transition: 'color 0.15s, background 0.15s',
          }}
        >
          <span style={{ fontSize: tall ? 12 : 9, opacity: 0.8 }}>{open ? '▾' : '▸'}</span>
          MENU
        </button>
        {open && (
          <div role="menu" style={{
            position: 'absolute', top: '100%', left: 0,
            minWidth: 320, zIndex: 100,
            background: 'var(--bg-2)',
            border: '1px solid var(--border-bright)',
            boxShadow: '0 12px 32px rgba(0,0,0,0.6)',
            padding: 6,
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.16em',
              color: 'var(--muted)', padding: '8px 12px 10px',
              borderBottom: '1px solid var(--border)',
            }}>SITEMAP</div>
            {items.map(it => {
              const active = it.sys === sys;
              return (
                <a key={it.sys} href={it.href} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '9px 12px',
                  fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em',
                  color: active ? 'var(--accent)' : 'var(--text-sec)',
                  textDecoration: 'none',
                  background: active ? 'var(--accent-glow)' : 'transparent',
                  borderLeft: `2px solid ${active ? 'var(--accent)' : 'transparent'}`,
                  transition: 'background 0.12s, color 0.12s',
                }}
                  onMouseEnter={e => { if (!active) { e.currentTarget.style.background = 'var(--surface)'; e.currentTarget.style.color = 'var(--text-pri)'; }}}
                  onMouseLeave={e => { if (!active) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-sec)'; }}}
                >
                  <span style={{ color: 'var(--muted)', minWidth: 56 }}>{it.sys}</span>
                  <span style={{ flex: 1 }}>{it.label}</span>
                  {active && <span style={{ color: 'var(--accent)', fontSize: 9 }}>● HERE</span>}
                </a>
              );
            })}
          </div>
        )}
      </div>

      {children}

      <div style={{ flex: 1 }} />

      <div style={{
        padding: '0 18px',
        display: 'flex', alignItems: 'center', gap: 8,
        fontFamily: 'var(--mono)', fontSize: FS, letterSpacing: '0.16em',
        borderLeft: '1px solid var(--border)', whiteSpace: 'nowrap',
      }}>
        <span style={{ color: 'var(--muted)' }}>{sys}</span>
        <span style={{ color: 'var(--border-bright)' }}>//</span>
        <span style={{ color: 'var(--accent)' }}>{name}</span>
      </div>
    </div>
  );
};

Object.assign(window, { SiteNav });

const PageBanner = ({ sys, title, subtitle }) => {
  return (
    <div style={{
      flexShrink: 0,
      borderBottom: '1px solid var(--border)',
      background: 'var(--bg-2)',
      padding: '20px 40px 18px',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 2,
        background: 'linear-gradient(to right, var(--accent), var(--accent-dim) 55%, transparent)',
        pointerEvents: 'none',
      }} />

      <div style={{
        position: 'absolute', right: 24, top: '50%',
        transform: 'translateY(-50%)',
        fontFamily: 'var(--sans-head)', fontWeight: 700,
        fontSize: 'clamp(48px, 6.5vw, 82px)',
        letterSpacing: '0.07em',
        color: 'var(--border-bright)', opacity: 0.3,
        userSelect: 'none', pointerEvents: 'none',
        lineHeight: 1,
      }}>{title}</div>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.22em',
          color: 'var(--accent)', marginBottom: 5,
        }}>{sys} · SECTION</div>
        <div style={{
          fontFamily: 'var(--sans-head)', fontWeight: 700,
          fontSize: 'clamp(22px, 2.8vw, 34px)',
          letterSpacing: '0.05em', lineHeight: 1,
          color: 'var(--text-pri)',
        }}>{title}</div>
        {subtitle && (
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em',
            color: 'var(--muted)', marginTop: 5,
          }}>{subtitle}</div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { PageBanner });
