/* ===== Home ===== */

/* faint background scenes for the what-is cards (flat outline, currentColor, low opacity via .card-motif) */
const MotifProgram = () => (
  <svg className="card-motif" width="360" height="208" viewBox="0 0 360 208" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round">
    {/* floating interface windows + connecting wires */}
    <rect x="58" y="14" width="64" height="44" rx="4" />
    <path d="M58 26 H122 M68 38 H104 M68 47 H92" />
    <rect x="148" y="6" width="56" height="40" rx="4" />
    <path d="M148 18 H204 M158 30 H188" />
    <rect x="230" y="16" width="62" height="42" rx="4" />
    <path d="M230 28 H292 M240 40 H276" />
    <g strokeDasharray="2 6" opacity="0.7"><path d="M90 58 V84 M176 46 V80 M261 58 V84" /></g>
    {/* desk */}
    <path d="M12 174 H348" />
    {/* a row of builders with laptops */}
    {[34, 116, 198, 280].map((x, i) => (
      <g key={i} transform={`translate(${x} 0)`}>
        <circle cx="22" cy="116" r="12" />
        <path d="M4 174 C4 144 40 144 40 174" />
        <path d="M8 174 L12 156 H32 L36 174 Z" />
        <path d="M12 156 H32" />
      </g>
    ))}
  </svg>
);
const MotifCommunity = () => (
  <svg className="card-motif" width="296" height="206" viewBox="0 0 296 206" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
    <g opacity="0.6"><path d="M52 70 L132 44 L212 78 L152 128 L52 70 M132 44 L152 128 M212 78 L248 150 L152 128 M52 70 L100 160 L152 128 M100 160 L248 150" /></g>
    {[[52, 70], [132, 44], [212, 78], [152, 128], [100, 160], [248, 150], [44, 150]].map(([x, y], i) => (
      <g key={i} transform={`translate(${x} ${y})`} fill="currentColor" stroke="none">
        <circle cx="0" cy="-4" r="5.4" />
        <path d="M-9 12 a9 10 0 0 1 18 0 Z" />
      </g>
    ))}
    <g>
      <rect x="166" y="18" width="38" height="25" rx="6" />
      <path d="M177 43 V51 L186 43" />
      <path d="M174 28 H196 M174 35 H187" strokeWidth="1.5" />
    </g>
  </svg>
);
const MotifProducts = () => (
  <svg className="card-motif" width="286" height="216" viewBox="0 0 286 216" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round">
    {[[14, 96], [66, 54], [118, 12]].map(([x, y], i) => (
      <g key={i} transform={`translate(${x} ${y})`}>
        <rect x="0" y="0" width="152" height="106" rx="6" fill="var(--bg-2)" />
        <path d="M0 22 H152" />
        <g fill="currentColor" stroke="none"><circle cx="14" cy="11" r="2.4" /><circle cx="24" cy="11" r="2.4" /><circle cx="34" cy="11" r="2.4" /></g>
        <rect x="14" y="36" width="46" height="48" rx="3" />
        <path d="M74 38 H138 M74 50 H120 M74 62 H132 M74 74 H106" />
      </g>
    ))}
  </svg>
);

/* barrier illustrations */
const CrowdArt = () => {
  const [ref, inView] = useInView({ threshold: 0.25 });
  const pts = [
    [40, 44, 0.9], [78, 38, 1], [116, 44, 0.9], [154, 38, 0.85], [192, 46, 0.8], [230, 40, 0.7],
    [22, 84, 0.85], [60, 80, 1], [98, 86, 0.95], [136, 80, 0.9], [174, 86, 0.85], [212, 82, 0.75], [248, 86, 0.65],
    [44, 120, 0.8], [82, 116, 0.9], [120, 122, 0.85], [158, 116, 0.8], [196, 122, 0.7],
  ];
  /* reveal bottom-to-top: rank figures by descending y so lower rows come first */
  const order = pts.map((_, i) => i).sort((a, b) => pts[b][1] - pts[a][1]);
  const rank = {}; order.forEach((idx, r) => { rank[idx] = r; });
  return (
    <div ref={ref} className={"ba-art" + (inView ? " in" : "")}>
      <svg width="280" height="150" viewBox="0 0 280 150" fill="#C44536" stroke="none">
        {pts.map(([x, y, o], i) => (
          <g key={i} transform={`translate(${x} ${y}) scale(0.92)`}>
            <g className="crowd-fig" style={{ "--o": o * 0.85, "--i": rank[i] }}>
              <circle cx="0" cy="0" r="5" />
              <path d="M-9 18 a9 11 0 0 1 18 0 Z" />
            </g>
          </g>
        ))}
      </svg>
    </div>
  );
};
const SoloArt = () => {
  const [ref, inView] = useInView({ threshold: 0.25 });
  return (
    <div ref={ref} className={"ba-art" + (inView ? " in" : "")}>
      <svg className="solo-art" width="280" height="160" viewBox="0 0 280 160" fill="none">
        <g className="solo-fig" fill="#C44536" stroke="none">
          <circle cx="52" cy="90" r="13" />
          <path d="M30 150 C 30 108 74 108 74 150 Z" />
        </g>
        <g>
          <rect x="116" y="34" width="150" height="104" rx="8" fill="#1a130d" stroke="#D85B43" strokeWidth="2" />
          <rect x="116" y="34" width="150" height="18" rx="8" fill="#241811" />
          <g fill="#C44536"><circle cx="130" cy="43" r="2.4" /><circle cx="140" cy="43" r="2.4" /><circle cx="150" cy="43" r="2.4" /></g>
          <rect x="132" y="68" width="118" height="40" rx="4" fill="#C44536" opacity="0.28" />
          <rect x="132" y="116" width="70" height="9" rx="3" fill="#E8973F" opacity="0.6" />
        </g>
        <path d="M78 120 L116 108" stroke="#C44536" strokeWidth="1.6" strokeDasharray="2 7" opacity="0.6" />
      </svg>
    </div>
  );
};

/* Scramble effect — символы «глючат» и складываются в слово (once on mount) */
function Scramble({ text, delay = 0, duration = 900, className = "" }) {
  const [out, setOut] = useState(text);
  useEffect(() => {
    const chars = "АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯXZQKWMSJHRLB0123456789/#*+=<>";
    let raf; let start = 0;
    const t0 = performance.now() + delay;
    const step = (now) => {
      if (now < t0) { raf = requestAnimationFrame(step); return; }
      if (!start) start = now;
      const p = Math.min(1, (now - start) / duration);
      const revealCount = Math.floor(p * text.length);
      let s = "";
      for (let i = 0; i < text.length; i++) {
        if (i < revealCount || text[i] === " " || text[i] === " ") { s += text[i]; }
        else { s += chars[(Math.floor(Math.random() * chars.length))]; }
      }
      setOut(s);
      if (p < 1) raf = requestAnimationFrame(step); else setOut(text);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [text, delay, duration]);
  return <span className={className}>{out}</span>;
}

/* Falling comets that streak across the hero every few seconds */
function Comets() {
  const seeds = [
    { top: "10%", delay: "3s", duration: "3.2s", opacity: 0.9 },
    { top: "22%", delay: "10s", duration: "3.8s", opacity: 0.7 },
    { top: "6%",  delay: "17s", duration: "3s",   opacity: 0.85 },
  ];
  return (
    <div className="hero-comets" aria-hidden="true">
      {seeds.map((s, i) => (
        <span key={i} className="comet" style={{ top: s.top, animationDelay: s.delay, animationDuration: s.duration, opacity: s.opacity }} />
      ))}
    </div>
  );
}

function HomePage() {
  return (
    <div>
      {/* HERO */}
      <header className="hero">
        <div className="hero-grid" />
        <HeroSky />
        <Comets />
        <Mountains />
        <div className="wrap hero-stamp-row">
          <div className="hero-stamp reveal d1">
            <span className="hs-dot"></span>
            <span className="hs-text">5 — 19 ИЮЛЯ 2026 · МАХАЧКАЛА</span>
            <span className="hs-flag">ПОТОК №1</span>
          </div>
        </div>
        <div className="wrap hero-body">
          <div className="hero-row">
            <h1 className="hero-title reveal d2"><Scramble text="Время" delay={500} duration={700} /><br /><span className="stroke"><Scramble text="строить." delay={1200} duration={1100} /></span><span className="hero-caret" aria-hidden="true"></span></h1>
            <div className="hero-aside reveal d3">
              <p className="hero-sub">AI-компания из Дагестана. Запускаем свои продукты и помогаем другим выпустить первые.</p>
            </div>
          </div>
          <div className="hero-actions reveal d4">
            <a className="btn-primary btn-pulse" href="#/apply">Присоединиться<span className="cta-tail"> к Поток №1</span> <Arrow s={18} /></a>
            <a className="btn-text" href="#/products">Что мы строим <Arrow s={16} /></a>
          </div>
        </div>
      </header>

      <Ornament />

      {/* ЧТО ТАКОЕ SORGENT — three parts */}
      <section className="sec alt">
        <div className="wrap">
          <div className="sec-head">
            <h2 className="sec-title">Что такое Sorgent?</h2>
            <p className="sec-lead">Программа на 2 недели. Сообщество, которое остаётся. Продукты, которые работают.</p>
          </div>
          <div className="what-grid">
            <a className="card lg" href="#/builders">
              <div className="card-head">
                <span className="card-idx">01 — ПРОГРАММА</span>
                <span className="card-ic"><IcTool s={48} /></span>
              </div>
              <div className="card-body">
                <h3>Программа Builders</h3>
                <p>2 недели. На выходе — твой первый рабочий продукт в интернете.</p>
              </div>
              <span className="card-more">Как присоединиться <Arrow s={14} /></span>
              <MotifProgram />
            </a>
            <div className="what-col">
              <a className="card sm" href="#/community">
                <div className="card-head">
                  <span className="card-idx">02 — СООБЩЕСТВО</span>
                  <span className="card-ic"><IcCommunity s={34} /></span>
                </div>
                <div className="card-body">
                  <h3>Sorgent Community</h3>
                  <p>Закрытый чат, оффлайн-встречи, совместные запуски. То, что начинается на программе, продолжается годами.</p>
                </div>
                <span className="card-more">Про сообщество <Arrow s={14} /></span>
                <MotifCommunity />
              </a>
              <a className="card sm" href="#/products">
                <div className="card-head">
                  <span className="card-idx">03 — ПРОДУКТЫ</span>
                  <span className="card-ic"><IcProjects s={34} /></span>
                </div>
                <div className="card-body">
                  <h3>Sorgent Products</h3>
                  <p>Свои AI-продукты, которыми сами пользуемся каждый день. Опыт от тех, кто в проде.</p>
                </div>
                <span className="card-more">Наши продукты <Arrow s={14} /></span>
                <MotifProducts />
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* МАНИФЕСТ — barrier card */}
      <section className="manifest">
        <div className="wrap">
          <div className="barrier-head">
            <div className="barrier-head-copy">
              <span className="rubric">Сейчас твой момент</span>
              <h2 className="barrier-title">Барьер<br /><span className="stroke">исчез.</span></h2>
              <p className="barrier-lead">Чтобы запустить продукт, раньше нужна была целая команда. Сегодня хватает одного человека с идеей.</p>
            </div>
            <Illo video="illo-chaos-solo.mp4" src="illo-chaos-solo.png" alt="Хаос толпы и один создатель, идущий вверх" max={440} anim="right" />
          </div>

          <div className="barrier-card">
            <div className="ba-col">
              <div className="ba-era">
                <span className="ba-era-num">/01</span>
                <span className="ba-era-lab">Раньше</span>
              </div>
              <CrowdArt />
              <p>Деньги, большая команда и месяцы работы. Чтобы собрать продукт, нужна была <b>толпа людей</b> и долгий путь.</p>
            </div>
            <div className="ba-col now">
              <div className="ba-era now">
                <span className="ba-era-num">/02</span>
                <span className="ba-era-lab">Сейчас</span>
              </div>
              <SoloArt />
              <p>Ноутбук, идея и желание попробовать. AI — инструмент, которым <b>один человек собирает большой продукт</b>.</p>
            </div>
          </div>

          <p className="barrier-final">
            <span className="bf-line1">Идея у тебя уже есть.</span>
            <br />
            <span className="bf-line2">Не хватает только <span className="hl">людей рядом</span> — и <span className="hl">двух недель</span>, чтобы не бросить.</span>
          </p>
        </div>
      </section>
    </div>
  );
}
window.HomePage = HomePage;
