// COVIA Resources — Atlas
// Section divided into 4 sub-chapters; auto-advances destination as you scroll.

function CoviaResources() {
  const { lang, t } = useLang();
  const sectionRef = React.useRef(null);
  const progress = useScrollProgress(sectionRef);

  const tabs = [
    { id: 'research',  num: 'I' },
    { id: 'platforms', num: 'II' },
    { id: 'learning',  num: 'III' },
    { id: 'media',     num: 'IV' },
  ];

  const resources = {
    research: [
      { name: 'OpenAI Blog',         url: 'https://openai.com/blog',                    desc: '模型發布與研究' },
      { name: 'Anthropic News',      url: 'https://www.anthropic.com/news',             desc: 'Claude 與安全 AI' },
      { name: 'DeepMind',            url: 'https://deepmind.google',                    desc: 'AI 理論與應用' },
      { name: 'arXiv AI',            url: 'https://arxiv.org/list/cs.AI/recent',        desc: '最新 AI 論文' },
      { name: 'arXiv ML',            url: 'https://arxiv.org/list/cs.LG/recent',        desc: '機器學習論文' },
      { name: 'Papers With Code',    url: 'https://paperswithcode.com/',                desc: '論文 + 代碼匯整' },
      { name: 'HuggingFace Papers',  url: 'https://huggingface.co/papers',              desc: '論文整合平台' },
      { name: 'Distill.pub',         url: 'https://distill.pub/',                       desc: '可視化 AI 研究' },
      { name: 'EleutherAI',          url: 'https://www.eleuther.ai/',                   desc: '開源 GPT 社群' },
      { name: 'Alignment Forum',     url: 'https://www.alignmentforum.org/',            desc: 'AI 對齊研究' },
    ],
    platforms: [
      { name: 'Claude',      url: 'https://claude.ai/',          desc: '深度推理' },
      { name: 'ChatGPT',     url: 'https://chatgpt.com/',        desc: '日常事務 + 圖像生成' },
      { name: 'Gemini',      url: 'https://gemini.google.com/',  desc: '深度研究' },
      { name: 'Grok',        url: 'https://grok.com/',           desc: '推理 + X 資訊集成' },
      { name: 'Perplexity',  url: 'https://www.perplexity.ai/',  desc: '資訊整合獲取' },
      { name: 'GitHub',      url: 'https://github.com/',         desc: '開源平台' },
      { name: 'Vercel',      url: 'https://vercel.com/',         desc: '前端部署' },
      { name: 'Cloudflare',  url: 'https://cloudflare.com/',     desc: '雲端基礎設施' },
      { name: 'HuggingFace', url: 'https://huggingface.co/',     desc: '開源 AI 平台' },
      { name: 'Kaggle',      url: 'https://www.kaggle.com/',     desc: 'ML 競賽 + GPU' },
    ],
    learning: [
      { name: 'DeepLearning.AI',     url: 'https://www.deeplearning.ai/the-batch/',     desc: 'Andrew Ng AI 教育' },
      { name: 'FreeCodeCamp',        url: 'https://www.freecodecamp.org/news/',         desc: '免費程式教學' },
      { name: 'KDNuggets',           url: 'https://www.kdnuggets.com/',                 desc: '資料科學趨勢' },
      { name: 'Analytics Vidhya',    url: 'https://www.analyticsvidhya.com/',           desc: 'AI 進階教學' },
      { name: 'AI Cup',              url: 'https://aicup.tw/',                          desc: '台灣 AI 競賽' },
      { name: 'TensorFlow Blog',     url: 'https://blog.tensorflow.org/',               desc: 'TF 官方動態' },
      { name: 'PyTorch Blog',        url: 'https://pytorch.org/blog/',                  desc: 'PyTorch 動態' },
      { name: 'LessWrong',           url: 'https://www.lesswrong.com/',                 desc: '理性思維 + AI 倫理' },
    ],
    media: [
      { name: 'Hacker News',         url: 'https://news.ycombinator.com',                desc: '科技/創業/AI 討論' },
      { name: 'TechCrunch AI',       url: 'https://techcrunch.com/tag/ai/',              desc: '科技新聞' },
      { name: 'VentureBeat AI',      url: 'https://venturebeat.com/category/ai/',        desc: '商業 AI 新聞' },
      { name: 'iThome',              url: 'https://www.ithome.com.tw/',                  desc: '台灣 IT 媒體' },
      { name: 'INSIDE',              url: 'https://www.inside.com.tw/',                  desc: '科技趨勢觀察' },
      { name: 'Stack Overflow Blog', url: 'https://stackoverflow.blog',                  desc: '開發者趨勢' },
      { name: 'Reddit ML',           url: 'https://www.reddit.com/r/MachineLearning/',   desc: 'ML 學術討論' },
      { name: 'Quanta Magazine',     url: 'https://www.quantamagazine.org/tag/artificial-intelligence/', desc: 'AI 深度報導' },
      { name: 'PanSci 泛科學',       url: 'https://pansci.asia/',                        desc: '科學知識普及' },
    ],
  };

  // Map progress (with 5% pad each end) to one of 4 sub-chapters.
  // Scroll only drives which sub-chapter is active; per-item fade-in
  // is handled by CSS animation + stage remount (key={active.id}).
  const isMobile = typeof window !== 'undefined' && window.innerWidth <= 880;

  const inner = norm(progress, 0.05, 0.95);
  const seg = 1 / tabs.length;
  const tabIdx = isMobile ? 0 : Math.min(tabs.length - 1, Math.floor(inner / seg));
  const localT = (inner - tabIdx * seg) / seg;
  const active = tabs[tabIdx];
  const list = resources[active.id];

  const renderItem = (r, i) => (
    <a
      key={r.name}
      href={r.url}
      target="_blank"
      rel="noopener noreferrer"
      className="atlas-item"
      style={{ '--i': i }}
    >
      <span className="atlas-item-idx">{String(i + 1).padStart(2, '0')}</span>
      <span className="atlas-item-name">{r.name}</span>
      <span className="atlas-item-desc">{t('res.desc.' + r.name)}</span>
      <span className="atlas-item-host">
        {(() => { try { return new URL(r.url).hostname.replace(/^www\./, ''); } catch { return ''; } })()}
      </span>
      <span className="atlas-item-arrow">↗</span>
    </a>
  );

  if (isMobile) {
    return (
      <section id="resources" ref={sectionRef} className="atlas atlas-mobile" style={{ position: 'relative' }}>
        <div className="atlas-bg" aria-hidden="true">
          {tabs.map((tab, i) => (
            <div
              key={tab.id}
              className="atlas-bg-layer is-active"
              style={{ backgroundImage: "url('/landing/assets/background" + (i + 1) + ".png')", opacity: 0.08 }}
            />
          ))}
        </div>
        <div className="atlas-mobile-inner">
          <header className="atlas-head">
            <div className="atlas-chapter">
              <span className="atlas-chapter-num">03</span>
              <span className="atlas-chapter-label">External Resources · Atlas</span>
            </div>
          </header>

          {tabs.map((tab) => (
            <div key={tab.id} className="atlas-mobile-group">
              <div className="atlas-mobile-group-head">
                <span className="atlas-mobile-group-num">{tab.num}</span>
                <h3 className="atlas-mobile-group-title">{t('res.tab.' + tab.id)}</h3>
              </div>
              <div className="atlas-list">
                {resources[tab.id].map(renderItem)}
              </div>
            </div>
          ))}
        </div>
      </section>
    );
  }

  return (
    <section
      id="resources"
      ref={sectionRef}
      className="atlas"
      style={{ height: `${tabs.length * 60}vh`, position: 'relative' }}
    >
      <div className="atlas-pin">
        <div className="atlas-bg" aria-hidden="true">
          {tabs.map((tab, i) => (
            <div
              key={tab.id}
              className={'atlas-bg-layer' + (i === tabIdx ? ' is-active' : '')}
              style={{ backgroundImage: "url('/landing/assets/background" + (i + 1) + ".png')" }}
            />
          ))}
        </div>

        <header className="atlas-head">
          <div className="atlas-chapter">
            <span className="atlas-chapter-num">03</span>
            <span className="atlas-chapter-label">External Resources · Atlas</span>
          </div>
          <div className="atlas-chapter-counter">
            <span className="atlas-cur">{active.num}</span>
            <span className="atlas-sep"> / </span>
            <span className="atlas-tot">IV</span>
          </div>
        </header>

        <div className="atlas-compass">
          {tabs.map((tab, i) => (
            <div
              key={tab.id}
              className={'atlas-seg' + (i === tabIdx ? ' is-active' : '') + (i < tabIdx ? ' is-past' : '')}
            >
              <div className="atlas-seg-track">
                <div
                  className="atlas-seg-fill"
                  style={{ width: i < tabIdx ? '100%' : i === tabIdx ? `${localT * 100}%` : '0%' }}
                />
              </div>
              <div className="atlas-seg-meta">
                <span className="atlas-seg-num">{tab.num}</span>
                <span className="atlas-seg-label">{t('res.tab.' + tab.id)}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="atlas-stage">
          <div className="atlas-stage-head">
            <div className="atlas-stage-num">{active.num}</div>
            <h3 className="atlas-stage-title">{t('res.tab.' + active.id)}</h3>
            <p className="atlas-stage-blurb">{t('res.blurb.' + active.id)}</p>
          </div>

          <div className="atlas-list" key={active.id}>
            {list.map(renderItem)}
          </div>
        </div>
      </div>
    </section>
  );
}

const atlasStyle = document.createElement('style');
atlasStyle.textContent = `
  .atlas-pin {
    position: sticky; top: 0;
    height: 100vh; min-height: 720px;
    display: grid;
    grid-template-rows: auto auto 1fr;
    padding: clamp(40px, 6vh, 72px) clamp(24px, 5vw, 80px);
    overflow: hidden;
  }

  /* Stage backgrounds */
  .atlas-bg {
    position: absolute;
    inset: 0;
    z-index: 0;
    pointer-events: none;
    overflow: hidden;
  }
  .atlas-bg-layer {
    position: absolute;
    inset: 0;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    opacity: 0;
    transition: opacity 1s ease;
  }
  .atlas-bg-layer.is-active {
    opacity: 0.12;
  }
  .atlas-head,
  .atlas-compass,
  .atlas-stage {
    position: relative;
    z-index: 1;
  }
  .atlas-head {
    display: flex; justify-content: space-between; align-items: baseline;
    margin-bottom: 24px;
  }
  .atlas-chapter {
    display: flex; align-items: baseline; gap: 12px;
    font-family: var(--font-mono); font-size: 11px;
    letter-spacing: 0.18em; text-transform: uppercase;
    color: var(--text-2);
  }
  .atlas-chapter-num { color: var(--gold); }
  .atlas-chapter-counter {
    font-family: var(--font-mono); font-size: 13px;
    color: var(--text-1); letter-spacing: 0.08em;
  }
  .atlas-cur { color: var(--gold); font-weight: 600; }
  .atlas-sep, .atlas-tot { color: var(--text-2); }

  .atlas-compass {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: clamp(32px, 5vh, 56px);
  }
  .atlas-seg {
    display: flex; flex-direction: column; gap: 8px;
    opacity: 0.4;
    transition: opacity 300ms;
  }
  .atlas-seg.is-active, .atlas-seg.is-past { opacity: 1; }
  .atlas-seg-track {
    height: 2px; background: var(--border-subtle);
    overflow: hidden;
  }
  .atlas-seg-fill {
    height: 100%; background: var(--gold);
    transition: width 100ms linear;
  }
  .atlas-seg-meta {
    display: flex; align-items: baseline; gap: 8px;
    font-family: var(--font-mono); font-size: 10px;
    letter-spacing: 0.18em; text-transform: uppercase;
  }
  .atlas-seg-num { color: var(--text-2); width: 24px; }
  .atlas-seg.is-active .atlas-seg-num,
  .atlas-seg.is-past .atlas-seg-num { color: var(--gold); }
  .atlas-seg-label { color: var(--text-1); }

  .atlas-stage {
    display: grid;
    grid-template-columns: minmax(280px, 1fr) 2fr;
    gap: clamp(40px, 6vw, 80px);
    align-items: start;
    overflow: hidden;
  }
  /* Text nodes in stage-head update in place on tab change — short
     color/opacity hint smooths the swap without full remount. */
  .atlas-stage-num, .atlas-stage-title, .atlas-stage-blurb {
    transition: color 240ms ease-out;
  }
  .atlas-stage-head { display: flex; flex-direction: column; gap: 16px; }
  .atlas-stage-num {
    font-family: var(--font-display);
    font-size: clamp(64px, 8vw, 120px);
    font-weight: 300;
    letter-spacing: 0.04em;
    line-height: 0.9;
    color: var(--gold);
  }
  .atlas-stage-title {
    font-family: var(--font-display);
    font-size: clamp(28px, 3.5vw, 44px);
    font-weight: 400;
    letter-spacing: -0.01em;
    color: var(--text-0);
    margin: 0;
  }
  .atlas-stage-blurb {
    font-size: 15px; line-height: 1.6;
    color: var(--text-2);
    max-width: 320px;
    margin: 0;
  }

  .atlas-list {
    display: flex; flex-direction: column;
    border-top: 1px solid var(--border-subtle);
  }

  .atlas-item {
    display: grid;
    grid-template-columns: 32px minmax(120px, 200px) 1fr 140px 16px;
    gap: 16px;
    align-items: center;
    padding: 9px 0;
    border-bottom: 1px solid var(--border-subtle);
    text-decoration: none;
    color: var(--text-1);
    transition: padding 240ms, color 240ms;
    will-change: opacity, transform;
    animation: atlasItemReveal 380ms cubic-bezier(0.22, 1, 0.36, 1) both;
    animation-delay: calc(var(--i, 0) * 35ms + 60ms);
  }
  .atlas-item-name { line-height: 1.25; }
  .atlas-item-desc { line-height: 1.3; }
  @keyframes atlasItemReveal {
    from { opacity: 0; transform: translateX(-16px); }
    to   { opacity: 1; transform: translateX(0); }
  }
  .atlas-item:hover {
    color: var(--text-0);
    padding-left: 12px;
  }
  .atlas-item:hover .atlas-item-arrow { color: var(--gold); transform: translate(2px, -2px); }
  .atlas-item:hover .atlas-item-host { color: var(--gold); }
  .atlas-item-idx {
    font-family: var(--font-mono); font-size: 10px;
    color: var(--text-2); letter-spacing: 0.08em;
  }
  .atlas-item-name {
    font-size: 15px; color: var(--text-0);
    letter-spacing: -0.005em;
  }
  .atlas-item-desc {
    font-size: 13px; color: var(--text-2);
  }
  .atlas-item-host {
    font-family: var(--font-mono); font-size: 11px;
    color: var(--text-2); letter-spacing: 0.04em;
    text-align: right;
    transition: color 200ms;
  }
  .atlas-item-arrow {
    color: var(--text-2);
    font-size: 14px;
    transition: color 200ms, transform 200ms;
  }

  /* Mobile — all groups stacked, no scroll-driven behavior */
  .atlas-mobile {
    height: auto !important;
    padding: clamp(40px, 6vh, 72px) clamp(16px, 4vw, 24px);
  }
  .atlas-mobile-inner {
    display: flex;
    flex-direction: column;
    gap: 32px;
  }
  .atlas-mobile-group {
    display: flex;
    flex-direction: column;
    gap: 0;
  }
  .atlas-mobile-group-head {
    display: flex;
    align-items: baseline;
    gap: 10px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border-subtle);
  }
  .atlas-mobile-group-num {
    font-family: var(--font-display);
    font-size: 24px;
    color: var(--gold);
    letter-spacing: 0.04em;
  }
  .atlas-mobile-group-title {
    font-family: var(--font-display);
    font-size: 18px;
    color: var(--text-0);
    margin: 0;
  }
  .atlas-mobile .atlas-item {
    grid-template-columns: 28px 1fr 16px;
  }
  .atlas-mobile .atlas-item-desc,
  .atlas-mobile .atlas-item-host { display: none; }
  .atlas-mobile .atlas-head { margin-bottom: 8px; }

  /* Desktop narrow fallback */
  @media (max-width: 880px) {
    .atlas:not(.atlas-mobile) { height: auto !important; min-height: 100vh; }
    .atlas-pin { position: static; height: auto; }
    .atlas-compass { grid-template-columns: 1fr 1fr; }
    .atlas-stage { grid-template-columns: 1fr; }
    .atlas-item { grid-template-columns: 28px 1fr 16px; }
    .atlas-item-desc, .atlas-item-host { display: none; }
  }
`;
document.head.appendChild(atlasStyle);

window.CoviaResources = CoviaResources;
