/* Hosted assets — single source of truth for what we serve at
   assets.nexusregen.com. Verified against the live R2 bucket
   (`public-assets`) on 2026-05-07. Drives both the Brand page
   "Hosted assets" section AND the For-agents page asset table. */

const HOSTED_ASSET_BASE = 'https://assets.nexusregen.com';

/* Each asset has a logical name + a map of available formats. The bucket
   uses inconsistent naming (some items have all three formats, some are
   svg+png only) so we model what actually exists, not what we wish was
   there. */
const HOSTED_ASSETS = [
  {
    group: 'Primary logos',
    note: 'The everyday wordmark + emblem. Default to SVG.',
    bg: 'paper',
    items: [
      { name: 'Main logo (horizontal)',  path: 'nr/main/nr-logo-main',     formats: ['svg','png','jpg'], demo: 'wide' },
      { name: 'Presentation logo',       path: 'nr/main/nr-logo-present',  formats: ['svg','png','jpg'], demo: 'wide' },
      { name: 'Main emblem',             path: 'nr/main/nr-emblem-main',   formats: ['svg','png','jpg'], demo: 'square' },
      { name: 'Main icon',               path: 'nr/main/nr-icon-main',     formats: ['svg','png','jpg'], demo: 'square' },
      { name: 'Icon (with shadow)',      path: 'nr/main/nr-icon-shdw',     formats: ['svg','png','jpg'], demo: 'square' },
    ],
  },
  {
    group: 'Horizontal logotype',
    note: 'Five colourways. Pick by background.',
    bg: 'paper',
    items: [
      { name: 'Black',                   path: 'nr/logotype/nr-logotype-black', formats: ['svg','png','jpg'], demo: 'wide', preferBg: 'paper' },
      { name: 'White',                   path: 'nr/logotype/nr-logotype-white', formats: ['svg','png','jpg'], demo: 'wide', preferBg: 'navy' },
      { name: 'Light',                   path: 'nr/logotype/nr-logotype-light', formats: ['svg','png','jpg'], demo: 'wide', preferBg: 'navy' },
      { name: 'Blue',                    path: 'nr/logotype/nr-logotype-blue',  formats: ['svg','png','jpg'], demo: 'wide', preferBg: 'paper' },
      { name: 'Dual (blue + yellow)',    path: 'nr/logotype/nr-logotype-dual',  formats: ['svg','png','jpg'], demo: 'wide', preferBg: 'paper' },
    ],
  },
  {
    group: 'Stacked logotype (vertical)',
    note: 'Squarer aspect. For tile-shaped placements.',
    bg: 'paper',
    items: [
      { name: 'Black',                   path: 'nr/stackedlogotype/nr-stackedlogotype-black',       formats: ['svg','png','jpg'], demo: 'square', preferBg: 'paper' },
      { name: 'Blue',                    path: 'nr/stackedlogotype/nr-stackedlogotype-blue',        formats: ['svg','png','jpg'], demo: 'square', preferBg: 'paper' },
      { name: 'White',                   path: 'nr/stackedlogotype/nr-stackedlogotype-white',       formats: ['svg','png','jpg'], demo: 'square', preferBg: 'navy' },
      { name: 'Yellow & white',          path: 'nr/stackedlogotype/nr-stackedlogotype-yellowwhite', formats: ['svg','png','jpg'], demo: 'square', preferBg: 'navy' },
    ],
  },
  {
    group: 'Emblem variants',
    note: 'Mark-only ramp. For favicons, app icons, partner tiles.',
    bg: 'paper',
    items: [
      { name: 'Black',                   path: 'nr/emblem/nr-emblem-black',  formats: ['svg','png','jpg'], demo: 'square', preferBg: 'paper' },
      { name: 'Blue',                    path: 'nr/emblem/nr-emblem-blue',   formats: ['svg','png','jpg'], demo: 'square', preferBg: 'paper' },
      { name: 'White',                   path: 'nr/emblem/nr-emblem-white',  formats: ['svg','png','jpg'], demo: 'square', preferBg: 'navy' },
      { name: 'Yellow',                  path: 'nr/emblem/nr-emblem-yellow', formats: ['svg','png','jpg'], demo: 'square', preferBg: 'navy' },
    ],
  },
  {
    group: 'Favicons & app icons',
    note: 'Pre-baked, 16/32/180/192/512 ready.',
    bg: 'paper',
    items: [
      { name: 'Favicon 1',               path: 'nr/icon/favicon1',              formats: ['svg','png'], demo: 'square' },
      { name: 'Favicon 2',               path: 'nr/icon/favicon2',              formats: ['svg','png'], demo: 'square' },
      { name: 'Favicon · filled',        path: 'nr/icon/favicon-filled',        formats: ['svg','png'], demo: 'square' },
      { name: 'Favicon · thick blue',    path: 'nr/icon/favicon-thick-blue',    formats: ['svg','png'], demo: 'square' },
      { name: 'Favicon · thick light blue', path: 'nr/icon/favicon-thick-lblue',formats: ['svg','png'], demo: 'square' },
      { name: 'Favicon · thick yellow',  path: 'nr/icon/favicon-thick-yellow',  formats: ['svg','png'], demo: 'square' },
      { name: 'Icon · blue rounded',     path: 'nr/icon/nr-icon-blue-rounded',  formats: ['svg','png'], demo: 'square' },
      { name: 'Icon · blue square',      path: 'nr/icon/nr-icon-blue-sq',       formats: ['svg','png'], demo: 'square' },
      { name: 'Icon · square arrow (yellow on blue)', path: 'nr/icon/nr-icon-sq-arrow-yellow_on_blue', formats: ['svg','png'], demo: 'square' },
    ],
  },
  {
    group: 'Backgrounds',
    note: 'Branded background fills. Use for hero sections, decks, social.',
    bg: 'paper',
    items: [
      { name: 'Background 1',            path: 'nr/bg/nr-bg-1', formats: ['svg','png','jpg'], demo: 'wide', preferBg: 'paper' },
    ],
  },
  {
    group: 'Legacy',
    note: 'Stable URL retained for backward compatibility.',
    bg: 'paper',
    items: [
      { name: 'Legacy logo',             path: 'logo', formats: ['png'], demo: 'wide' },
    ],
  },
];

/* Build a flat list of {label, url} for the agents page table. */
function hostedAssetsFlat() {
  const out = [];
  HOSTED_ASSETS.forEach(g => {
    g.items.forEach(it => {
      it.formats.forEach(f => {
        out.push({
          group: g.group,
          label: `${it.name} · ${f.toUpperCase()}`,
          url: `${HOSTED_ASSET_BASE}/${it.path}.${f}`,
        });
      });
    });
  });
  return out;
}

/* Asset card with preview + format-specific copy buttons */
function HostedAssetCard({ item, defaultBg }) {
  const [copied, setCopied] = useState(null);
  const [previewFmt, setPreviewFmt] = useState(item.formats.includes('svg') ? 'svg' : item.formats[0]);
  const url = (fmt) => `${HOSTED_ASSET_BASE}/${item.path}.${fmt}`;
  const onCopy = (fmt) => {
    copy(url(fmt));
    setCopied(fmt);
    setTimeout(() => setCopied(null), 1100);
  };
  const bgKey = item.preferBg || defaultBg || 'paper';
  const bgStyle = bgKey === 'navy'
    ? { background: 'var(--brand-600)' }
    : bgKey === 'check'
    ? { background: 'repeating-conic-gradient(rgba(0,0,0,.04) 0% 25%, transparent 0% 50%) 0 / 16px 16px' }
    : { background: 'var(--bg-secondary)' };

  return (
    <div style={{
      border: '1px solid var(--border-secondary)',
      borderRadius: 12,
      overflow: 'hidden',
      background: 'var(--bg-primary)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Preview */}
      <div style={{
        ...bgStyle,
        height: item.demo === 'wide' ? 132 : 168,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 18,
        position: 'relative',
        borderBottom: '1px solid var(--border-tertiary)',
      }}>
        <img
          src={url(previewFmt)}
          alt={item.name}
          style={{
            maxWidth: '100%', maxHeight: '100%',
            objectFit: 'contain',
            display: 'block',
          }}
          loading="lazy"
        />
        {/* Tiny preview-format toggle so users can sanity-check raster output too */}
        {item.formats.length > 1 && (
          <div style={{
            position: 'absolute', top: 8, right: 8,
            display: 'flex', gap: 2, padding: 2, borderRadius: 6,
            background: 'rgba(255,255,255,.85)',
            backdropFilter: 'blur(6px)',
          }}>
            {item.formats.map(f => (
              <button key={f} onClick={() => setPreviewFmt(f)} style={{
                border: 'none',
                background: previewFmt === f ? 'var(--brand-600)' : 'transparent',
                color: previewFmt === f ? '#fff' : 'var(--text-tertiary)',
                fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
                padding: '3px 7px', borderRadius: 4, cursor: 'pointer',
                textTransform: 'uppercase', letterSpacing: '.04em',
              }}>{f}</button>
            ))}
          </div>
        )}
      </div>

      {/* Label + copy buttons */}
      <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>
            {item.name}
          </div>
          <code style={{
            display: 'block',
            fontFamily: 'var(--font-mono)', fontSize: 10,
            color: 'var(--text-quaternary)', marginTop: 2,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{item.path}</code>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          {item.formats.map(f => (
            <button key={f} onClick={() => onCopy(f)} title={`Copy ${url(f)}`}
              style={{
                flex: 1,
                border: '1px solid var(--border-secondary)',
                background: copied === f ? 'var(--brand-600)' : 'var(--bg-secondary)',
                color: copied === f ? '#fff' : 'var(--text-secondary)',
                fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700,
                padding: '7px 4px', borderRadius: 6, cursor: 'pointer',
                textTransform: 'uppercase', letterSpacing: '.04em',
              }}>
              {copied === f ? '✓' : f}
            </button>
          ))}
          <a href={url(previewFmt)} target="_blank" rel="noopener" title="Open in new tab"
            style={{
              border: '1px solid var(--border-secondary)',
              background: 'var(--bg-secondary)',
              color: 'var(--text-secondary)',
              padding: '7px 9px', borderRadius: 6,
              fontSize: 12, textDecoration: 'none',
            }}>↗</a>
        </div>
      </div>
    </div>
  );
}

function S_HostedAssets() {
  const [search, setSearch] = useState('');
  return (
    <Section
      id="hosted-assets"
      eyebrow="11 · Hosted assets"
      title="Stable URLs for everything visible."
      intro="Every brand asset on this page is served from the public-assets R2 bucket at https://assets.nexusregen.com — already CDN-cached and ready to embed in product code, READMEs, partner tiles, and email signatures. SVG is preferred for everything web; PNG / JPG mirrors exist for places vector isn't supported."
    >
      <Block title="Search">
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Filter by name or path…"
          style={{
            width: '100%', maxWidth: 420,
            padding: '10px 14px',
            border: '1px solid var(--border-primary)', borderRadius: 8,
            background: 'var(--bg-primary)', color: 'var(--text-primary)',
            fontSize: 14, fontFamily: 'inherit', outline: 'none',
          }}
        />
      </Block>

      {HOSTED_ASSETS.map(group => {
        const q = search.trim().toLowerCase();
        const items = q
          ? group.items.filter(it =>
              it.name.toLowerCase().includes(q) ||
              it.path.toLowerCase().includes(q) ||
              group.group.toLowerCase().includes(q))
          : group.items;
        if (!items.length) return null;
        return (
          <Block key={group.group} title={group.group} note={group.note}>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
              gap: 14,
            }}>
              {items.map(it => (
                <HostedAssetCard key={it.path} item={it} defaultBg={group.bg} />
              ))}
            </div>
          </Block>
        );
      })}

      <Block title="Notes" note="Limitations and quirks to be aware of.">
        <Card pad={20}>
          <ul style={{ margin: 0, paddingLeft: 18, fontSize: 14, lineHeight: 1.7,
            color: 'var(--text-secondary)' }}>
            <li>The bucket also contains an older <code style={{ fontFamily: 'var(--font-mono)' }}>Nexus-ReGen-Brand-Kit/…</code> hierarchy
              (~140 files) — not surfaced here. Prefer the <code style={{ fontFamily: 'var(--font-mono)' }}>nr/…</code> paths above for new work.</li>
            <li>The user-supplied <code style={{ fontFamily: 'var(--font-mono)' }}>nr-icon-blue-square</code> entries (large variant) return 404 — only the <em>small</em> <code style={{ fontFamily: 'var(--font-mono)' }}>nr-icon-blue-sq</code> exists. The large one was never uploaded.</li>
            <li>SVGs are the source. PNG / JPG are pre-rendered exports — convenient, but use SVG wherever a vector is acceptable.</li>
            <li>Bucket is public + CDN-fronted by Cloudflare, so caching is aggressive. Expect ~1 hour TTL on changed assets unless you cache-bust.</li>
          </ul>
        </Card>
      </Block>
    </Section>
  );
}

window.HOSTED_ASSETS = HOSTED_ASSETS;
window.HOSTED_ASSET_BASE = HOSTED_ASSET_BASE;
window.hostedAssetsFlat = hostedAssetsFlat;
window.S_HostedAssets = S_HostedAssets;
