/* ============================================================
   CHAINUS — shared UI primitives
   ============================================================ */

function Logo({ height = 24 }) {
  return (
    <span className="logo-wrap" style={{ height }}>
      <img className="logo-img logo-dark" src="chainus-logo.png" alt="ChainUs" style={{ height }} draggable="false" />
      <img className="logo-img logo-light" src="chainus-logo-white2.png" alt="" aria-hidden="true" style={{ height }} draggable="false" />
    </span>
  );
}

function ArrowIcon() { return <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>; }
function ChevronIcon() { return <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>; }
function AppleGlyph() { return <svg className="ico" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M16.7 12.7c0-2.3 1.9-3.4 2-3.5-1.1-1.6-2.8-1.8-3.4-1.8-1.4-.1-2.8.8-3.5.8-.7 0-1.8-.8-3-.8-1.5 0-3 .9-3.8 2.3-1.6 2.8-.4 7 1.2 9.3.8 1.1 1.7 2.4 2.9 2.3 1.2 0 1.6-.7 3-.7s1.8.7 3 .7 2-1 2.8-2.1c.9-1.3 1.2-2.5 1.3-2.6-.1 0-2.5-1-2.5-3.9zM14.5 6c.6-.8 1-1.9.9-3-.9 0-2 .6-2.7 1.4-.6.7-1.1 1.8-.9 2.8 1 .1 2-.5 2.7-1.2z" /></svg>; }
function PlayGlyph() { return <svg className="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 3.5v17c0 .6.6 1 1.1.7L19 12.6c.5-.3.5-1 0-1.3L5.1 2.8C4.6 2.5 4 2.9 4 3.5z" fill="currentColor" /></svg>; }

function Glyph({ kind, w = 22 }) {
  const s = { width: w, height: w };
  const k = { stroke: 'currentColor', strokeWidth: 1.8, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'feed') return <svg viewBox="0 0 24 24" {...s}><rect x="3" y="4" width="18" height="6" rx="2" {...k} /><rect x="3" y="14" width="12" height="6" rx="2" {...k} /><circle cx="19" cy="17" r="2" {...k} /></svg>;
  if (kind === 'tokenize') return <svg viewBox="0 0 24 24" {...s}><path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z" {...k} /><circle cx="12" cy="12" r="3" {...k} /></svg>;
  if (kind === 'learn') return <svg viewBox="0 0 24 24" {...s}><circle cx="12" cy="12" r="8" {...k} /><path d="M12 8v4l3 2" {...k} /></svg>;
  if (kind === 'intel') return <svg viewBox="0 0 24 24" {...s}><path d="M4 16l4-5 4 3 4-7 4 6" {...k} /><circle cx="8" cy="11" r="1.4" fill="currentColor" stroke="none" /><circle cx="16" cy="7" r="1.4" fill="currentColor" stroke="none" /></svg>;
  if (kind === 'shield') return <svg viewBox="0 0 24 24" {...s}><path d="M12 3l7 3v5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6l7-3z" {...k} /><path d="M9 12l2 2 4-4" {...k} /></svg>;
  if (kind === 'eye') return <svg viewBox="0 0 24 24" {...s}><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z" {...k} /><circle cx="12" cy="12" r="2.5" {...k} /></svg>;
  if (kind === 'key') return <svg viewBox="0 0 24 24" {...s}><circle cx="8" cy="8" r="4" {...k} /><path d="M11 11l8 8M16 16l2-2M19 19l2-2" {...k} /></svg>;
  if (kind === 'exit') return <svg viewBox="0 0 24 24" {...s}><path d="M14 4h4a2 2 0 012 2v12a2 2 0 01-2 2h-4M10 12H3m0 0l3-3m-3 3l3 3" {...k} /></svg>;
  if (kind === 'phone') return <svg viewBox="0 0 24 24" {...s}><rect x="7" y="2" width="10" height="20" rx="3" {...k} /><path d="M11 18h2" {...k} /></svg>;
  if (kind === 'web') return <svg viewBox="0 0 24 24" {...s}><rect x="3" y="4" width="18" height="14" rx="2" {...k} /><path d="M3 8h18M8 22h8M12 18v4" {...k} /></svg>;
  if (kind === 'sync') return <svg viewBox="0 0 24 24" {...s}><path d="M4 12a8 8 0 0113-6m3 6a8 8 0 01-13 6" {...k} /><path d="M17 3v3h-3M7 21v-3h3" {...k} /></svg>;
  if (kind === 'spark') return <svg viewBox="0 0 24 24" {...s}><path d="M12 3v6m0 6v6M5 8l2 2m10 4l2 2M3 12h6m6 0h6M5 16l2-2m10-4l2-2" {...k} /></svg>;
  if (kind === 'cart') return <svg viewBox="0 0 24 24" {...s}><path d="M3 4h2l2.4 12.4a1 1 0 001 .8h9.2a1 1 0 001-.8L21 8H6" {...k} /><circle cx="9" cy="20" r="1.2" fill="currentColor" stroke="none" /><circle cx="18" cy="20" r="1.2" fill="currentColor" stroke="none" /></svg>;
  if (kind === 'chart') return <svg viewBox="0 0 24 24" {...s}><path d="M4 4v16h16" {...k} /><rect x="7" y="11" width="3" height="6" {...k} /><rect x="13" y="7" width="3" height="10" {...k} /></svg>;
  if (kind === 'book') return <svg viewBox="0 0 24 24" {...s}><path d="M4 5a2 2 0 012-2h6v16H6a2 2 0 00-2 2V5z" {...k} /><path d="M20 5a2 2 0 00-2-2h-6v16h6a2 2 0 012 2V5z" {...k} /></svg>;
  if (kind === 'globe') return <svg viewBox="0 0 24 24" {...s}><circle cx="12" cy="12" r="9" {...k} /><path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18" {...k} /></svg>;
  if (kind === 'bolt') return <svg viewBox="0 0 24 24" {...s}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z" {...k} /></svg>;
  if (kind === 'tag') return <svg viewBox="0 0 24 24" {...s}><path d="M3 12V5a2 2 0 012-2h7l9 9-9 9-9-9z" {...k} /><circle cx="8" cy="8" r="1.4" fill="currentColor" stroke="none" /></svg>;
  if (kind === 'gas') return <svg viewBox="0 0 24 24" {...s}><rect x="4" y="4" width="9" height="16" rx="1.5" {...k} /><path d="M13 9h3.5a1.5 1.5 0 011.5 1.5V16a1.5 1.5 0 003 0V8l-2-2" {...k} /></svg>;
  return null;
}

/* App Store + Google Play badges */
function StoreBadges({ t }) {
  return (
    <div className="store-row">
      <button className="store-badge">
        <AppleGlyph />
        <span className="tt"><small>{t.dir === 'zh' ? '即将上线' : 'Coming to'}</small><b>App Store</b></span>
        <span className="soon">soon</span>
      </button>
      <button className="store-badge">
        <PlayGlyph />
        <span className="tt"><small>{t.dir === 'zh' ? '即将上线' : 'Coming to'}</small><b>Google Play</b></span>
        <span className="soon">soon</span>
      </button>
    </div>
  );
}

function MagneticButton({ children, className = '', onClick, style }) {
  const ref = useMagnetic(0.22);
  return <button ref={ref} className={`magnetic ${className}`} onClick={onClick} style={style}>{children}</button>;
}

/* Theme toggle — sun/moon morph */
function ThemeToggle({ theme, onToggle }) {
  const dark = theme === 'dark';
  return (
    <button className="theme-toggle" onClick={onToggle} aria-label="Toggle theme" title={dark ? 'Switch to light' : 'Switch to dark'}>
      <span className={`tt-track ${dark ? 'dark' : 'light'}`}>
        <span className="tt-knob">
          {dark
            ? <svg viewBox="0 0 24 24" width="13" height="13" fill="none"><path d="M21 12.8A9 9 0 1111.2 3a7 7 0 009.8 9.8z" fill="currentColor"/></svg>
            : <svg viewBox="0 0 24 24" width="13" height="13" fill="none"><circle cx="12" cy="12" r="4.2" fill="currentColor"/><path d="M12 2v2.5M12 19.5V22M4.2 4.2l1.8 1.8M18 18l1.8 1.8M2 12h2.5M19.5 12H22M4.2 19.8L6 18M18 6l1.8-1.8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>}
        </span>
      </span>
    </button>
  );
}

function FramePreview({ slotId = '', type = 'web', placeholder = '' }) {
  const id = String(slotId).toLowerCase();
  const mode = id.includes('market') || id.includes('web') ? 'market'
    : id.includes('token') || id.includes('mint') ? 'mint'
    : id.includes('tablet') || id.includes('sync') ? 'sync'
    : 'feed';
  const title = mode === 'market' ? 'Market pulse' : mode === 'mint' ? 'Token studio' : mode === 'sync' ? 'Synced workspace' : 'Community feed';
  const metric = mode === 'market' ? '+12.8%' : mode === 'mint' ? 'Ready' : mode === 'sync' ? 'Live' : '24K';
  const chips = mode === 'market' ? ['BTC', 'RWA', 'NFT'] : mode === 'mint' ? ['Upload', 'Price', 'Mint'] : mode === 'sync' ? ['Mobile', 'Web', 'Tablet'] : ['Follow', 'Discuss', 'Collect'];
  const rows = mode === 'market'
    ? [['ETH', '$3,892', '+2.4%'], ['SOL', '$164', '+4.8%'], ['RWA', '$82M', '+8.1%']]
    : mode === 'mint'
      ? [['Digital work', 'Verified', 'Ready'], ['Royalty', '2.5%', 'Set'], ['Listing', 'Fixed', 'Live']]
      : mode === 'sync'
        ? [['Feed draft', 'Mobile', 'Saved'], ['Market watch', 'Web', 'Open'], ['Mint status', 'Tablet', 'Synced']]
      : [['NovaDAO', 'Proposal live', '18K'], ['RWA desk', 'Token drop', '6.4K'], ['ChainUs', placeholder || 'Daily brief', '2.1K']];

  return (
    <div className={`frame-preview fp-${type} fp-${mode}`} aria-hidden="true">
      <div className="fp-top">
        <span className="fp-brand">ChainUs</span>
        <span className="fp-pill">Live</span>
      </div>
      <div className="fp-hero">
        <span>{title}</span>
        <b className="tnum">{metric}</b>
      </div>
      <div className="fp-chips">
        {chips.map((chip) => <span key={chip}>{chip}</span>)}
      </div>
      <div className="fp-main">
        <div className="fp-chart">
          {Array.from({ length: 14 }).map((_, i) => <i key={i} style={{ '--h': `${24 + ((i * 19) % 58)}%` }}></i>)}
        </div>
        <div className="fp-list">
          {rows.map((row) => (
            <div className="fp-row" key={row.join('-')}>
              <span>{row[0]}</span>
              <b>{row[1]}</b>
              <em>{row[2]}</em>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

const FRAME_SHOTS = {
  'hero-web': 'assets/v3/overview-page-desktop.png',
  'hero-phone': 'assets/v3/overview-page-mobile.png',
  'feature-feed': 'assets/v3/feed-mobile.jpg',
  'any-phone': 'assets/v3/overview-page-mobile.png',
  'any-web': 'assets/v3/overview-page-desktop.png',
  'any-tablet': 'assets/v3/market-page-desktop.png',
  'shot-home': 'assets/v3/feed-mobile.jpg',
  'shot-tokenize': 'assets/v3/nft-page-mobile.png',
  'shot-market': 'assets/v3/market-page-mobile.png'
};

function frameShotFor(slotId = '', type = 'web') {
  if (Object.prototype.hasOwnProperty.call(FRAME_SHOTS, slotId)) return FRAME_SHOTS[slotId];
  if (type === 'phone') return 'assets/v3/overview-page-mobile.png';
  if (type === 'tablet') return 'assets/v3/market-page-desktop.png';
  return 'assets/v3/overview-page-desktop.png';
}

/* Phone frame */
function PhoneFrame({ slotId, placeholder, width = 280, children, glow = false }) {
  const h = Math.round(width * 2.04);
  const shot = frameShotFor(slotId, 'phone');
  return (
    <div className={`phone ${glow ? 'phone-glow' : ''}`} style={{ width, height: h }}>
      <div className="phone-bezel">
        <div className="phone-island"></div>
        <div className="phone-screen">
          <image-slot id={slotId} src={shot} shape="rect" placeholder={placeholder} style={{ width: '100%', height: '100%', borderRadius: 0 }}></image-slot>
          {children || (!shot && <FramePreview slotId={slotId} type="phone" placeholder={placeholder} />)}
        </div>
      </div>
    </div>
  );
}

/* Desktop / browser window */
function DesktopFrame({ slotId, placeholder, url = 'chainus.org', children, className = '', ratio = '16 / 10' }) {
  const shot = frameShotFor(slotId, 'web');
  return (
    <div className={`web-frame ${className}`}>
      <div className="web-bar">
        <span className="web-lights"><i></i><i></i><i></i></span>
        <span className="web-url"><span className="web-lock" aria-hidden="true"></span>{url}</span>
        <span className="web-bar-sp"></span>
      </div>
      <div className="web-screen" style={{ aspectRatio: ratio }}>
        <image-slot id={slotId} src={shot} shape="rect" placeholder={placeholder} style={{ width: '100%', height: '100%', borderRadius: 0 }}></image-slot>
        {children || (!shot && <FramePreview slotId={slotId} type="web" placeholder={placeholder} />)}
      </div>
    </div>
  );
}

/* Tablet frame */
function TabletFrame({ slotId, placeholder, width = 360, children }) {
  const h = Math.round(width * 1.34);
  const shot = frameShotFor(slotId, 'tablet');
  return (
    <div className="tablet" style={{ width, height: h }}>
      <div className="tablet-bezel">
        <div className="tablet-screen">
          <image-slot id={slotId} src={shot} shape="rect" placeholder={placeholder} style={{ width: '100%', height: '100%', borderRadius: 0 }}></image-slot>
          {children || (!shot && <FramePreview slotId={slotId} type="tablet" placeholder={placeholder} />)}
        </div>
      </div>
    </div>
  );
}

/* Ecosystem wordmark marquee (quiet) */
function Logos({ t }) {
  const names = ['Ledgerly', 'NovaPay', 'Mintlab', 'Polychain', 'Aurora', 'Beacon', 'Driftwave', 'Helios'];
  const row = names.concat(names);
  return (
    <section className="logos">
      <div className="wrap">
        <p className="logos-label tag">{t.dir === 'zh' ? '与 120+ 链上社区与团队共建' : 'Trusted across 120+ on-chain communities & teams'}</p>
        <div className="logos-track marquee-mask">
          <div className="marquee" style={{ '--dur': '50s' }}>
            {row.map((n, i) => <span key={i} className="logo-word">{n}</span>)}
          </div>
        </div>
      </div>
    </section>
  );
}

function SectionHead({ eyebrow, title, sub, center, max, align, showEyebrow = false }) {
  return (
    <div className={`sec-head ${center ? 'center' : ''}`} style={{ ...(max ? { maxWidth: max } : null), ...(align ? { textAlign: align } : null) }}>
      {showEyebrow && eyebrow && <Reveal className="eyebrow" as="span">{eyebrow}</Reveal>}
      <Reveal as="h2" className="h2 sec-title" delay={60} style={{ marginTop: 14 }}>{title}</Reveal>
      {sub && <Reveal className="lead sec-sub" delay={120} style={{ marginTop: 14, ...(center ? { marginInline: 'auto' } : {}) }}>{sub}</Reveal>}
    </div>
  );
}

Object.assign(window, {
  Logo, ArrowIcon, ChevronIcon, AppleGlyph, PlayGlyph, Glyph,
  StoreBadges, MagneticButton, ThemeToggle, FramePreview, frameShotFor, PhoneFrame, DesktopFrame, TabletFrame, Logos, SectionHead
});
