// shared.jsx — Constellation theme primitives
// Loaded on every page. Exports to window.

const GITHUB_URL = 'https://github.com/joshua-ivy/Delyx';
const ISSUE_URL  = 'https://github.com/joshua-ivy/Delyx/issues/new';
const LATEST_GITHUB_STATUS_URLS = [
  'https://us-central1-delyx-7968b.cloudfunctions.net/getGithubStatusFeed',
  '/latest-reasoning-status.json',
];

async function loadLatestGithubStatus() {
  for (const url of LATEST_GITHUB_STATUS_URLS) {
    try {
      const response = await fetch(url + (url.includes('?') ? '&' : '?') + 'v=' + Date.now(), {
        headers: { Accept: 'application/json' },
        cache: 'no-store',
      });
      if (!response.ok) continue;
      const payload = await response.json();
      if (payload && payload.schemaVersion === 1 && Array.isArray(payload.bullets)) {
        return payload;
      }
    } catch (error) {
      console.warn('GitHub status feed unavailable from ' + url, error);
    }
  }
  return null;
}

function statusToneColor(tone) {
  if (tone === 'red' || tone === 'bad') return 'var(--c-red)';
  if (tone === 'amber' || tone === 'warn' || tone === 'tech' || tone === 'gap') return 'var(--c-amber)';
  return 'var(--c-green)';
}

function statusDate(value) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return 'latest status';
  return date.toLocaleString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });
}

// ──────────────────────────── Starfield ────────────────────────────

function Starfield({ density = 220 }) {
  const stars = React.useMemo(() => {
    const s = [];
    const rand = (i) => {
      const x = Math.sin(i * 9301 + 49297) * 233280;
      return x - Math.floor(x);
    };
    for (let i = 0; i < density; i++) {
      s.push({
        x: rand(i) * 100,
        y: rand(i + 500) * 100,
        r: rand(i + 1000) * 1.4 + 0.3,
        o: rand(i + 1500) * 0.6 + 0.2,
        d: rand(i + 2000) * 3 + 2,
      });
    }
    return s;
  }, [density]);
  return (
    <svg style={{
      position: 'fixed', inset: 0, width: '100%', height: '100%',
      pointerEvents: 'none', zIndex: 0,
    }} aria-hidden="true">
      {stars.map((s, i) => (
        <circle key={i} cx={s.x + '%'} cy={s.y + '%'} r={s.r} fill="#fff" opacity={s.o}>
          <animate attributeName="opacity" values={`${s.o};${s.o * 0.3};${s.o}`} dur={s.d + 's'} repeatCount="indefinite" />
        </circle>
      ))}
    </svg>
  );
}

// ──────────────────────────── Star Mark / Logo ────────────────────────────

function StarMark({ size = 24 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
      <g stroke="var(--c-cyan)" strokeWidth="0.7" fill="none">
        <circle cx="12" cy="12" r="3.2" fill="var(--c-cyan)" />
        <circle cx="4"  cy="6"  r="1.2" fill="var(--c-cyan)" />
        <circle cx="20" cy="8"  r="1.2" fill="var(--c-cyan)" />
        <circle cx="18" cy="20" r="1.2" fill="var(--c-cyan)" />
        <circle cx="5"  cy="18" r="1.2" fill="var(--c-cyan)" />
        <line x1="12" y1="12" x2="4"  y2="6"  opacity="0.6" />
        <line x1="12" y1="12" x2="20" y2="8"  opacity="0.6" />
        <line x1="12" y1="12" x2="18" y2="20" opacity="0.6" />
        <line x1="12" y1="12" x2="5"  y2="18" opacity="0.6" />
      </g>
    </svg>
  );
}

// ──────────────────────────── Nav ────────────────────────────

function Nav({ active }) {
  const links = [
    { id: 'home',    href: 'index.html',   label: 'home' },
    { id: 'docs',    href: 'docs.html',    label: 'docs' },
    { id: 'status',  href: 'status.html',  label: 'status' },
    { id: 'contact', href: 'contact.html', label: 'contact' },
  ];
  return (
    <header className="c-nav">
      <div className="c-nav-inner">
        <a className="c-brand" href="index.html">
          <StarMark size={22} />
          <span className="c-name">delyx</span>
          <span className="c-ver">v0.1.0 · alpha</span>
        </a>
        <nav className="c-nav-links">
          {links.map((l) => (
            <a key={l.id} href={l.href} className={active === l.id ? 'active' : ''}>{l.label}</a>
          ))}
          <a className="c-cta" href={GITHUB_URL + '/releases'} target="_blank" rel="noreferrer">get delyx →</a>
        </nav>
      </div>
    </header>
  );
}

// ──────────────────────────── Footer ────────────────────────────

function Footer() {
  return (
    <footer className="c-footer">
      <div>delyx · local-agent · {new Date().getFullYear()}</div>
      <div className="c-foot-mid">
        <a href="index.html">home</a>
        <a href="docs.html">docs</a>
        <a href="status.html">status</a>
        <a href="contact.html">contact</a>
        <a href={GITHUB_URL} target="_blank" rel="noreferrer">github ↗</a>
      </div>
      <div className="c-foot-end">v0.1.0 · windows-first · {'<<< ☆ >>>'}</div>
    </footer>
  );
}

// ──────────────────────────── Section Header ────────────────────────────

function SectionHeader({ code, eyebrow, title }) {
  return (
    <div style={{ marginBottom: 32 }}>
      <div className="c-section-h">
        <span>{code}</span>
        <span className="c-rule" />
        <span className="c-eyebrow">{eyebrow.toUpperCase()}</span>
      </div>
      <h2 className="c-section-title">{title}</h2>
    </div>
  );
}

// ──────────────────────────── Page header (eyebrow + big H1) ────────────────────────────

function PageHero({ eyebrow, title, sub, children }) {
  return (
    <section className="c-page-hero" style={{ padding: '70px 0 50px', position: 'relative', zIndex: 2 }}>
      <div className="c-pill" style={{ marginBottom: 24 }}>
        <span className="c-dot" />
        {eyebrow}
      </div>
      <h1 className="c-hero-title" style={{
        fontFamily: 'var(--c-sans)',
        fontSize: 'clamp(48px, 7vw, 88px)',
        lineHeight: 0.96,
        margin: 0, fontWeight: 400, letterSpacing: '-2px',
      }}>{title}</h1>
      {sub && (
        <p className="c-hero-sub" style={{
          color: 'var(--c-dim)', fontSize: 17,
          lineHeight: 1.55, maxWidth: 620, marginTop: 22,
        }}>{sub}</p>
      )}
      {children}
    </section>
  );
}

// ──────────────────────────── Callout ────────────────────────────

function Callout({ kind = 'note', children }) {
  const cls =
    'c-callout' +
    (kind === 'warn' ? ' c-callout-warn' :
     kind === 'bad'  ? ' c-callout-bad'  : '');
  const label = kind === 'warn' ? '⚠ heads up' :
                kind === 'bad'  ? '✕ careful'   : '★ note';
  return (
    <div className={cls}>
      <span className="c-ckind">{label}</span>
      {children}
    </div>
  );
}

// ──────────────────────────── Code block ────────────────────────────

function CodeBlock({ title, children }) {
  return (
    <div style={{
      background: 'rgba(0,0,0,0.35)',
      border: '1px solid var(--c-line)',
      borderRadius: 10,
      overflow: 'hidden',
      margin: '14px 0',
    }}>
      {title && (
        <div style={{
          padding: '9px 14px',
          borderBottom: '1px solid var(--c-line)',
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 10.5, color: 'var(--c-mute)',
          letterSpacing: 1.5, textTransform: 'uppercase',
          fontFamily: 'var(--c-mono)',
        }}>
          <span style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--c-red)', opacity: 0.7 }} />
          <span style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--c-amber)', opacity: 0.7 }} />
          <span style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--c-green)', opacity: 0.7 }} />
          <span style={{ marginLeft: 8 }}>{title}</span>
        </div>
      )}
      <pre style={{
        margin: 0, padding: '14px 16px',
        fontFamily: 'var(--c-mono)', fontSize: 12.5, lineHeight: 1.75,
        color: 'var(--c-fg-2)', whiteSpace: 'pre-wrap', overflowX: 'auto',
      }}>{children}</pre>
    </div>
  );
}

// ──────────────────────────── Hash heading link ────────────────────────────

function H({ id, children }) {
  return <h2 id={id}><span className="c-hash">#</span>{children}</h2>;
}

// ──────────────────────────── Table ────────────────────────────

function Table({ rows }) {
  return (
    <table className="c-table"><tbody>
      {rows.map(([a, b], i) => (
        <tr key={i}><td>{a}</td><td>{b}</td></tr>
      ))}
    </tbody></table>
  );
}

// ──────────────────────────── Export ────────────────────────────

Object.assign(window, {
  GITHUB_URL, ISSUE_URL,
  loadLatestGithubStatus, statusToneColor, statusDate,
  Starfield, StarMark, Nav, Footer,
  SectionHeader, PageHero, Callout, CodeBlock, H, Table,
});
