import { createRoot } from 'react-dom/client';
import { useEffect } from 'react';
import Dither from './Dither';
import TextType from './TextType';
import ScrollStack, { ScrollStackItem } from './ScrollStack';
import './hero.css';

const Hero = () => (
  <section className="identity-card atlas-card dither-hero" aria-label="UsonTong 首页介绍">
    <div className="hero-dither" aria-hidden="true">
      <Dither
        waveColor={[0.3686274509803922, 0.5254901960784314, 0.611764705882353]}
        disableAnimation={false}
        enableMouseInteraction={false}
        mouseRadius={0.3}
        colorNum={4.9}
        pixelSize={2}
        waveAmplitude={0.35}
        waveFrequency={3}
        waveSpeed={0.08}
      />
    </div>
    <div className="hero-surface" aria-hidden="true" />
    <div className="identity-copy">
      <TextType
        as="h1"
        className="identity-lead identity-type"
        text={'Follow rule\n\u2003find meaning'}
        typingSpeed={120}
        initialDelay={180}
        pauseDuration={2400}
        deletingSpeed={38}
        loop={false}
        showCursor={true}
        cursorCharacter="|"
        cursorBlinkDuration={0.55}
        startOnVisible={true}
      />
    </div>
    <aside className="presence-card" aria-label="开发者资料">
      <div className="portrait">
        <img src="/assets/avatar.jpg" alt="UsonTong 的 GitHub 头像" />
        <span />
      </div>
      <h2>UsonTong</h2>
      <p>@UsonTong</p>
      <dl>
        <div>
          <dt>关注方向</dt>
          <dd>AI 工作流 · 后端开发 · Linux</dd>
        </div>
        <div>
          <dt>正在构建</dt>
          <dd>xists</dd>
        </div>
      </dl>
      <a href="https://github.com/UsonTong" target="_blank" rel="noreferrer">
        github.com/UsonTong <span aria-hidden="true">↗</span>
      </a>
    </aside>
  </section>
);

const XistsCard = () => (
  <article className="project-card project-card-xists stack-project-inner">
    <a
      className="project-preview"
      href="https://github.com/UsonTong/xists"
      target="_blank"
      rel="noreferrer"
      aria-label="在 GitHub 查看 xists"
    >
      <img className="xists-cover-mark" src="/assets/xists-mark.svg" alt="" />
      <div className="xists-cover-copy">
        <p className="xists-cover-tagline">Find what exists. Decide what&apos;s next.</p>
      </div>
    </a>
    <div className="project-card-body">
      <div>
        <h3>xists</h3>
        <p>
          xists 是一个面向 GitHub 仓库清单的本地语义搜索工具。找到可直接使用、部署、改造或学习的已有项目，再决定下一步怎么做。
        </p>
      </div>
      <a
        className="work-arrow"
        href="https://github.com/UsonTong/xists"
        target="_blank"
        rel="noreferrer"
        aria-label="在 GitHub 查看 xists"
      >
        <i data-lucide="arrow-up-right" />
      </a>
    </div>
  </article>
);

const CotocoCard = () => (
  <article className="project-card project-card-cotoco stack-project-inner">
    <a
      className="project-preview"
      href="https://github.com/UsonTong/cotoco"
      target="_blank"
      rel="noreferrer"
      aria-label="在 GitHub 查看 cotoco"
    >
      <div className="cotoco-mark">
        <span>CO</span>
        <span>TO</span>
        <span>CO</span>
      </div>
      <p className="cotoco-pronounce">/kəʊ&apos;təʊkəʊ/</p>
      <p className="cotoco-line">
        From <b>co</b>de snippet <b>to</b> <b>co</b>mponent.
      </p>
      <div className="cotoco-pipeline">
        <span>AI 预审</span>
        <i />
        <span>沙箱测试</span>
        <i />
        <span>人工复核</span>
      </div>
    </a>
    <div className="project-card-body">
      <div>
        <h3>cotoco</h3>
        <p>从代码片段出发，经 AI 预审、沙箱测试与人工复核，让可运行的实现沉淀为可信的可复用零件。</p>
      </div>
      <a
        className="work-arrow"
        href="https://github.com/UsonTong/cotoco"
        target="_blank"
        rel="noreferrer"
        aria-label="在 GitHub 查看 cotoco"
      >
        <i data-lucide="arrow-up-right" />
      </a>
    </div>
  </article>
);

const GithubCard = () => (
  <section className="github-section atlas-card stack-panel" aria-labelledby="github-title">
    <div className="github-profile-layout">
      <div className="github-profile-main">
        <div className="github-title-row">
          <div>
            <h3 id="github-title">GitHub 贡献</h3>
          </div>
          <p id="github-contribution-copy" className="github-year-total">
            <span id="github-contribution-total">--</span> commits
          </p>
        </div>
        <div className="github-heatmap" aria-label="UsonTong 的 GitHub contribution graph">
          <div className="github-calendar">
            <div id="github-months" className="github-months" aria-hidden="true" />
            <div className="github-graph">
              <div className="github-days" aria-hidden="true">
                <span />
                <span>周二</span>
                <span />
                <span>周四</span>
                <span />
                <span>周六</span>
                <span />
              </div>
              <div id="github-grid" className="github-grid" role="grid" />
            </div>
          </div>
          <div className="github-heatmap-foot">
            <a
              href="https://docs.github.com/account-and-profile/reference/profile-contributions-reference"
              target="_blank"
              rel="noreferrer"
            >
              贡献记录说明
            </a>
            <span className="github-scale">
              少 <i className="level-0" />
              <i className="level-1" />
              <i className="level-2" />
              <i className="level-3" />
              <i className="level-4" /> 多
            </span>
          </div>
          <div id="github-tooltip" className="github-tooltip" role="status" />
        </div>
      </div>
      <nav id="github-years" className="github-years" aria-label="Contribution years" />
    </div>
  </section>
);

const TokenCard = () => (
  <section className="token-usage-embed atlas-card stack-panel" aria-labelledby="calendar-title">
    <div className="token-profile-layout">
      <div className="token-profile-main">
        <div className="calendar-head">
          <div>
            <h3 id="calendar-title">Token 使用</h3>
          </div>
          <p id="token-year-total" className="github-year-total">
            -- tokens
          </p>
        </div>
        <div className="heatmap" aria-label="2026 年 Token 使用日历">
          <div className="heatmap-months" id="heatmap-months" />
          <div className="heatmap-layout">
            <div className="heatmap-days">
              <span />
              <span>周二</span>
              <span />
              <span>周四</span>
              <span />
              <span>周六</span>
              <span />
            </div>
            <div className="heatmap-grid" id="heatmap-grid" />
          </div>
          <div className="chart-tooltip" id="chart-tooltip" role="status" />
          <div className="heatmap-foot">
            <span className="scale">
              少 <i className="level-0" />
              <i className="level-1" />
              <i className="level-2" />
              <i className="level-3" />
              <i className="level-4" /> 多
            </span>
          </div>
        </div>
        <dl className="usage-summary" id="usage-summary">
          <div>
            <dt>累计用量</dt>
            <dd>
              <span id="usage-total">--</span> <small>tokens</small>
            </dd>
          </div>
          <div>
            <dt>每日平均用量</dt>
            <dd>
              <span id="usage-calendar-average">--</span> <small>tokens</small>
            </dd>
          </div>
          <div>
            <dt>活跃日平均用量</dt>
            <dd>
              <span id="usage-active-average">--</span> <small>tokens</small>
            </dd>
          </div>
        </dl>
      </div>
      <nav id="token-years" className="github-years token-years" aria-label="Token usage years" />
    </div>
    <section className="model-mix" aria-labelledby="model-mix-title">
      <div className="model-mix-copy">
        <h3 id="model-mix-title">
          模型 <em>用量</em>
        </h3>
      </div>
      <div className="donut-wrap">
        <svg id="model-donut" className="model-donut" viewBox="0 0 220 220" role="img" aria-label="模型 token 使用占比" />
        <div className="donut-center">
          <b id="donut-total" />
        </div>
        <div id="donut-tooltip" className="donut-tooltip" />
      </div>
      <div id="model-legend" className="model-legend" />
    </section>
  </section>
);

const ClosingCard = () => (
  <section className="closing-section stack-panel" aria-label="近况与联系信息">
    <div className="closing-card atlas-card">
      <div className="closing-now">
        <h2>
          有想法，<em>欢迎聊聊。</em>
        </h2>
        <p>我在制作 xists 和 cotoco，也乐于交流开发者工具、AI 工作流与后端开发。</p>
      </div>
      <div className="closing-contact">
        <button className="contact-email copy-email" type="button" data-email="usontong@gmail.com">
          usontong@gmail.com <i data-lucide="copy" />
        </button>
        <p className="contact-note">（备注来意）</p>
      </div>
    </div>
  </section>
);

function loadScript(src) {
  return new Promise((resolve, reject) => {
    const existing = document.querySelector(`script[data-stack-src="${src}"]`);
    if (existing) {
      resolve();
      return;
    }
    const script = document.createElement('script');
    script.src = src;
    script.async = false;
    script.dataset.stackSrc = src;
    script.onload = () => resolve();
    script.onerror = () => reject(new Error(`Failed to load ${src}`));
    document.body.appendChild(script);
  });
}

const App = () => {
  useEffect(() => {
    let cancelled = false;

    const boot = async () => {
      // Wait one frame so ScrollStack cards and chart roots exist in the DOM.
      await new Promise(resolve => requestAnimationFrame(() => resolve()));
      if (cancelled) return;

      if (window.lucide?.createIcons) window.lucide.createIcons();

      try {
        await loadScript('/github-contributions.js?v=15');
        await loadScript('/usage.js?v=20260725-16');
      } catch (error) {
        console.warn(error);
      }

      document.querySelectorAll('.copy-email').forEach(button => {
        if (button.dataset.bound === '1') return;
        button.dataset.bound = '1';
        button.addEventListener('click', async () => {
          const email = button.dataset.email;
          const toast = document.querySelector('.toast');
          try {
            await navigator.clipboard.writeText(email);
          } catch {
            const input = document.createElement('input');
            input.value = email;
            document.body.append(input);
            input.select();
            document.execCommand('copy');
            input.remove();
          }
          if (toast) {
            toast.classList.add('show');
            setTimeout(() => toast.classList.remove('show'), 1800);
          }
        });
      });
    };

    boot();
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <ScrollStack
      className="site-scroll-stack"
      itemDistance={160}
      itemScale={0}
      itemStackDistance={14}
      stackPosition="12%"
      scaleEndPosition="12%"
      baseScale={1}
      rotationAmount={0}
      blurAmount={0}
      useWindowScroll={false}
    >
      <ScrollStackItem itemClassName="stack-chapter stack-hero">
        <Hero />
      </ScrollStackItem>
      <ScrollStackItem itemClassName="stack-chapter stack-work stack-xists">
        <XistsCard />
      </ScrollStackItem>
      <ScrollStackItem itemClassName="stack-chapter stack-work stack-cotoco">
        <CotocoCard />
      </ScrollStackItem>
      <ScrollStackItem itemClassName="stack-chapter stack-github">
        <GithubCard />
      </ScrollStackItem>
      <ScrollStackItem itemClassName="stack-chapter stack-token">
        <TokenCard />
      </ScrollStackItem>
      <ScrollStackItem itemClassName="stack-chapter stack-closing">
        <ClosingCard />
      </ScrollStackItem>
    </ScrollStack>
  );
};

const mount = document.querySelector('#app');
if (mount) createRoot(mount).render(<App />);
