// ════════════════════════════════════════════════════════════════
// Secondary pages: Markets, Methodologies, Costs
// ════════════════════════════════════════════════════════════════

function MarketSection() {
  const D = window.SDH_DATA;
  return (
    <div className="sdh-fade">
      <section className="sdh-container" style={{ paddingTop: 'var(--space-12)', paddingBottom: 'var(--space-8)' }}>
        <span className="sdh-section-label">рынки · обзор сегментов</span>
        <h1 className="sdh-hero-h" style={{ marginBottom: 'var(--space-3)' }}>
          Шесть <em>сегментов</em> в фокусе наблюдения
        </h1>
        <p className="sdh-quote" style={{ maxWidth: 720, margin: 0 }}>
          Размер рынка приведён к мировому объёму за 2025 год по открытым источникам. Темп роста рассчитан на скользящем окне 12 месяцев.
        </p>
        <span className="sdh-sep" />

        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
          gap: 'var(--space-4)',
        }}>
          {D.markets.map(m => (
            <div key={m.id} className="sdh-warm-card" style={{ '--bg-tint': `var(--hue-${m.hue}-subtle)` }}>
              <div className="sdh-mono-label" style={{ marginBottom: 6 }}>сегмент</div>
              <h3 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: 'var(--text-primary)', letterSpacing: '-0.01em', marginBottom: 'var(--space-3)' }}>
                {m.name}
              </h3>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 'var(--space-3)' }}>
                <span className="sdh-metric-big">${m.size_usd_b}</span>
                <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>млрд</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <MomentumPill momentum={m.growth > 0 ? 'rising' : 'cooling'} growth={m.growth} />
                <span className="sdh-mono-label">CAGR 12 мес</span>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

function MethodologiesSection() {
  const D = window.SDH_DATA;
  const [openId, setOpenId] = React.useState(null);
  const [layout, setLayout] = React.useState('families'); // 'families' | 'grid'

  // Group by family
  const byFamily = D.FAMILIES.map(f => ({
    family: f,
    items: D.methodologies.filter(m => m.family === f.id),
  }));

  const openMethod = openId ? D.methodologies.find(m => m.id === openId) : null;

  return (
    <div className="sdh-fade">
      {/* HERO */}
      <section className="sdh-container" style={{ paddingTop: 'var(--space-12)', paddingBottom: 'var(--space-6)' }}>
        <span className="sdh-section-label">методологии · 14 протоколов · 4 семьи</span>
        <h1 className="sdh-hero-h" style={{ marginBottom: 'var(--space-3)' }}>
          Инструментарий <em>Орлова</em> для синтеза
        </h1>
        <p className="sdh-quote" style={{ maxWidth: 720, margin: 0 }}>
          Четыре семьи объединяют все 14 методологий. Каждая идея размечена связанным протоколом, что позволяет навигировать корпус через метод, а не только через нишу.
        </p>
      </section>

      <CommandBar sticky={false}
        left={
          <>
            <span className="sdh-mono-label" style={{ marginRight: 6 }}>раскладка</span>
            <button className={`sdh-chip ${layout === 'families' ? 'is-active' : ''}`} onClick={() => setLayout('families')}>
              по семьям
            </button>
            <button className={`sdh-chip ${layout === 'grid' ? 'is-active' : ''}`} onClick={() => setLayout('grid')}>
              сеткой
            </button>
          </>
        }
        right={<span className="sdh-mono-label">кликните на карточку для деталей</span>}
      />

      <section className="sdh-container" style={{ paddingTop: 'var(--space-6)', paddingBottom: 'var(--space-16)' }}>
        {layout === 'families' ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-12)' }}>
            {byFamily.map(({ family, items }) => (
              <FamilyBlock key={family.id} family={family} items={items} onOpen={setOpenId} />
            ))}
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
            gap: 'var(--space-4)',
          }}>
            {D.methodologies.map(m => (
              <MethodCard key={m.id} method={m} onOpen={() => setOpenId(m.id)} />
            ))}
          </div>
        )}
      </section>

      {openMethod && <MethodDetailModal method={openMethod} onClose={() => setOpenId(null)} />}
    </div>
  );
}

// ── Family block (grouped layout) ────────────────────────────────
function FamilyBlock({ family, items, onOpen }) {
  const totalIdeas = items.reduce((s, m) => s + m.ideas, 0);
  return (
    <section data-family={family.id}>
      {/* Family heading row */}
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 'var(--space-4)',
        padding: 'var(--space-3) 0 var(--space-4)',
        borderBottom: `1px solid var(--hue-${family.hue})`,
        marginBottom: 'var(--space-6)',
      }}>
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600,
          color: `var(--hue-${family.hue})`, letterSpacing: '0.06em',
        }}>{(family.label2 || family.label).toUpperCase()}</span>
        <h3 style={{
          margin: 0, fontFamily: 'var(--font-display)', fontStyle: 'italic',
          fontSize: 22, fontWeight: 500, color: 'var(--text-primary)',
          letterSpacing: '-0.015em',
        }}>{family.full}</h3>
        <span style={{ flex: 1, height: 1, background: 'var(--border-subtle)', marginLeft: 'var(--space-3)' }} />
        <span className="sdh-mono-label" style={{ marginBottom: 0 }}>
          {items.length} протоколов · {totalIdeas} идей
        </span>
      </div>

      {/* Cards */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))',
        gap: 'var(--space-4)',
      }}>
        {items.map(m => (
          <MethodCard key={m.id} method={m} onOpen={() => onOpen && onOpen(m.id)} />
        ))}
      </div>
    </section>
  );
}

// ── Method card ──────────────────────────────────────────────────
function MethodCard({ method, onOpen }) {
  const D = window.SDH_DATA;
  const totalIdeas = D.ideas.length;
  const sharePct = Math.round((method.ideas / totalIdeas) * 100);

  // Deterministic mini usage series (12 weeks)
  const series = React.useMemo(() => {
    const seed = method.id.charCodeAt(0) * 13 + method.ideas;
    const out = [];
    for (let i = 0; i < 12; i++) {
      const v = 0.4 + ((Math.sin(seed + i * 0.7) + 1) * 0.4) + ((seed + i * 3) % 7) / 18;
      out.push({ value: v });
    }
    return out;
  }, [method.id, method.ideas]);

  return (
    <button onClick={onOpen}
      className="sdh-warm-card"
      data-method={method.id}
      style={{
        '--bg-tint': `var(--hue-${method.hue}-subtle)`,
        padding: 'var(--space-6)',
        display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
        textAlign: 'left',
        border: '1px solid var(--border-subtle)',
        cursor: 'pointer',
        width: '100%',
        minHeight: 220,
      }}>
      {/* Head: family pill + meta */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <CategoryPill hue={method.hue} small>{(D.FAMILIES.find(f => f.id === method.family).label2 || D.FAMILIES.find(f => f.id === method.family).label).toUpperCase()}</CategoryPill>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)' }}>
          {method.year}
        </span>
      </div>

      {/* Title */}
      <div>
        <h3 style={{
          margin: 0, fontSize: 17, fontWeight: 600,
          color: 'var(--text-primary)', letterSpacing: '-0.01em',
          lineHeight: 1.25, marginBottom: 4,
        }}>{method.title}</h3>
        <p style={{
          margin: 0, fontFamily: 'var(--font-serif-body)', fontStyle: 'italic',
          fontSize: 13, color: 'var(--text-tertiary)', lineHeight: 1.35,
        }}>
          {method.tagline} · {method.author}
        </p>
      </div>

      {/* What */}
      <p style={{
        margin: 0, fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5,
        flex: 1,
      }}>
        {method.what}
      </p>

      {/* Key concepts as chips */}
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
        {method.concepts.slice(0, 4).map(c => (
          <span key={c} style={{
            display: 'inline-block',
            fontFamily: 'var(--font-mono)', fontSize: 10.5,
            padding: '2px 7px',
            background: 'var(--surface-elevated)',
            border: '1px solid var(--border-subtle)',
            borderRadius: 'var(--radius-full)',
            color: 'var(--text-tertiary)',
            whiteSpace: 'nowrap',
          }}>{c}</span>
        ))}
      </div>

      {/* Footer: ideas count + sparkline */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 12, paddingTop: 'var(--space-3)', borderTop: '1px solid var(--border-subtle)',
      }}>
        <div>
          <div className="sdh-mono-label" style={{ marginBottom: 1 }}>покрытие портфеля</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 500, color: 'var(--text-primary)' }}>
              {method.ideas}
            </span>
            <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>идей</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: `var(--hue-${method.hue})`, marginLeft: 4 }}>
              {sharePct}%
            </span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <MicroSparkline data={series} width={64} height={20} color={`var(--hue-${method.hue})`} fill accentLast />
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4"
               style={{ color: 'var(--brand-bronze)' }}>
            <path d="M4 7h6m-3-3 3 3-3 3" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      </div>
    </button>
  );
}

// ── Detail modal ─────────────────────────────────────────────────
function MethodDetailModal({ method, onClose }) {
  const D = window.SDH_DATA;
  const family = D.FAMILIES.find(f => f.id === method.family);
  const ideasUsing = D.ideas.filter(i => i.family === method.family).slice(0, 6);

  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'var(--surface-overlay)', zIndex: 100,
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: 'var(--space-8) var(--space-4)', overflowY: 'auto',
      backdropFilter: 'blur(2px)',
    }}>
      <div onClick={e => e.stopPropagation()} className="sdh-fade" style={{
        background: 'var(--surface-elevated)',
        borderRadius: 'var(--radius-2xl)',
        border: '1px solid var(--border-subtle)',
        maxWidth: 880, width: '100%',
        boxShadow: 'var(--shadow-xl)',
        overflow: 'hidden',
        position: 'relative',
      }}>
        <button className="sdh-btn sdh-btn--ghost" onClick={onClose}
          style={{ position: 'absolute', top: 14, right: 14, padding: 6, zIndex: 2 }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M3 3l8 8m0-8l-8 8" strokeLinecap="round" />
          </svg>
        </button>

        {/* Hero */}
        <div style={{
          padding: 'var(--space-8)',
          background: `linear-gradient(180deg, var(--hue-${method.hue}-subtle), var(--surface-elevated))`,
          borderBottom: '1px solid var(--border-subtle)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 'var(--space-3)' }}>
            <CategoryPill hue={method.hue}>{(family.label2 || family.label).toUpperCase()}</CategoryPill>
            <span className="sdh-mono-label" style={{ marginBottom: 0 }}>{family.full}</span>
          </div>
          <h2 style={{
            margin: 0, fontSize: 30, fontWeight: 600, letterSpacing: '-0.025em',
            color: 'var(--text-primary)', lineHeight: 1.15,
          }}>{method.title}</h2>
          <p style={{
            margin: 'var(--space-2) 0 0', fontFamily: 'var(--font-display)', fontStyle: 'italic',
            fontSize: 18, color: 'var(--brand-bronze-deep)', fontWeight: 500,
          }}>
            {method.tagline}
          </p>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 'var(--space-4)' }}>
            <span className="sdh-pill">
              <span style={{ fontFamily: 'var(--font-mono)' }}>{method.author}</span>
              <span style={{ color: 'var(--text-tertiary)' }}>{method.year}</span>
            </span>
            <span className="sdh-pill">
              <span style={{ fontFamily: 'var(--font-mono)', color: `var(--hue-${method.hue})` }}>{method.ideas}</span>
              <span style={{ color: 'var(--text-secondary)' }}>идей используют</span>
            </span>
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: 'var(--space-8)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 'var(--space-8)' }}>
            {/* Left */}
            <div>
              <h4 className="sdh-section-label">суть метода</h4>
              <p style={{ margin: '0 0 var(--space-4)', fontSize: 15, color: 'var(--text-primary)', lineHeight: 1.55 }}>
                {method.what}
              </p>

              <h4 className="sdh-section-label">когда применять</h4>
              <p className="sdh-quote" style={{
                margin: '0 0 var(--space-4)',
                padding: 'var(--space-3) var(--space-4)',
                borderLeft: `2px solid var(--hue-${method.hue})`,
                background: `var(--hue-${method.hue}-subtle)`,
                borderRadius: '0 var(--radius-md) var(--radius-md) 0',
                color: 'var(--text-primary)',
              }}>
                {method.bestFor}
              </p>

              <h4 className="sdh-section-label">ключевые понятия</h4>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 'var(--space-3)' }}>
                {method.concepts.map(c => (
                  <span key={c} style={{
                    fontFamily: 'var(--font-mono)', fontSize: 12,
                    padding: '4px 10px',
                    background: 'var(--surface-sunken)',
                    borderRadius: 'var(--radius-full)',
                    color: 'var(--text-primary)',
                    border: '1px solid var(--border-subtle)',
                  }}>{c}</span>
                ))}
              </div>
            </div>

            {/* Right */}
            <div>
              <h4 className="sdh-section-label">идеи, использующие метод</h4>
              <div style={{
                display: 'flex', flexDirection: 'column', gap: 4,
                marginBottom: 'var(--space-4)',
              }}>
                {ideasUsing.map(idea => (
                  <div key={idea.number} style={{
                    display: 'grid', gridTemplateColumns: '28px 1fr',
                    gap: 8, alignItems: 'center',
                    padding: '8px 10px',
                    background: 'var(--surface-elevated)',
                    border: '1px solid var(--border-subtle)',
                    borderRadius: 'var(--radius-md)',
                  }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--text-tertiary)' }}>
                      №{String(idea.number).padStart(2, '0')}
                    </span>
                    <span style={{
                      fontSize: 12.5, color: 'var(--text-primary)', lineHeight: 1.3,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>{idea.title}</span>
                  </div>
                ))}
              </div>
              {method.ideas > 6 && (
                <button className="sdh-btn sdh-btn--ghost" style={{ width: '100%', justifyContent: 'center', fontSize: 12 }}>
                  показать все {method.ideas} идей семьи
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: 'var(--space-4) var(--space-8)',
          borderTop: '1px solid var(--border-subtle)',
          background: 'var(--surface-sunken)',
        }}>
          <span className="sdh-mono-label" style={{ marginBottom: 0 }}>
            <span className="sdh-kbd">esc</span> закрыть
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="sdh-btn sdh-btn--ghost" onClick={onClose}>Закрыть</button>
            <button className="sdh-btn sdh-btn--bronze">
              Открыть идеи семьи
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.5">
                <path d="M3 6h6m-3-3 3 3-3 3" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function CostsPage() {
  const D = window.SDH_DATA;
  const items = [
    { label: 'эмбеддинги корпуса', usd: 142.30, calls: 11304, hue: 'info' },
    { label: 'кластеризация трендов', usd: 38.50, calls: 1872, hue: 'emerald' },
    { label: 'reranker для близости', usd: 64.15, calls: 5022, hue: 'amber' },
    { label: 'синтез вердиктов конкурентов', usd: 89.42, calls: 412, hue: 'rose' },
    { label: 'граф связанных идей', usd: 27.80, calls: 304, hue: 'purple' },
  ];
  const total = items.reduce((s, i) => s + i.usd, 0);
  const callsTotal = items.reduce((s, i) => s + i.calls, 0);

  return (
    <div className="sdh-fade">
      <section className="sdh-container" style={{ paddingTop: 'var(--space-12)', paddingBottom: 'var(--space-16)' }}>
        <span className="sdh-section-label">учёт · API расходы за май 2026</span>
        <h1 className="sdh-hero-h" style={{ marginBottom: 'var(--space-3)' }}>
          Стоимость <em>обработки</em> корпуса
        </h1>

        <div style={{
          marginTop: 'var(--space-8)',
          display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 'var(--space-4)',
        }}>
          <div className="sdh-warm-card" style={{ '--bg-tint': 'var(--brand-bronze-subtle)', padding: 'var(--space-4)' }}>
            <div className="sdh-mono-label" style={{ marginBottom: 4 }}>всего за месяц</div>
            <span className="sdh-metric-big">${total.toFixed(2)}</span>
          </div>
          <div className="sdh-warm-card" style={{ '--bg-tint': 'var(--hue-info-subtle)', padding: 'var(--space-4)' }}>
            <div className="sdh-mono-label" style={{ marginBottom: 4 }}>всего вызовов API</div>
            <span className="sdh-metric-big">{callsTotal.toLocaleString('ru-RU')}</span>
          </div>
          <div className="sdh-warm-card" style={{ '--bg-tint': 'var(--hue-emerald-subtle)', padding: 'var(--space-4)' }}>
            <div className="sdh-mono-label" style={{ marginBottom: 4 }}>стоимость на идею</div>
            <span className="sdh-metric-big">${(total / D.ideas.length).toFixed(2)}</span>
          </div>
          <div className="sdh-warm-card" style={{ '--bg-tint': 'var(--hue-amber-subtle)', padding: 'var(--space-4)' }}>
            <div className="sdh-mono-label" style={{ marginBottom: 4 }}>стоимость на стартап</div>
            <span className="sdh-metric-big">${(total / D.corpus.length * 100).toFixed(2)}<span style={{ fontSize: 14, color: 'var(--text-tertiary)' }}>¢</span></span>
          </div>
        </div>

        <span className="sdh-sep" />

        <div style={{
          border: '1px solid var(--border-subtle)',
          borderRadius: 'var(--radius-xl)',
          background: 'var(--surface-elevated)',
          overflow: 'hidden',
        }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 140px 140px 120px',
            padding: '12px 20px',
            background: 'var(--surface-sunken)',
            borderBottom: '1px solid var(--border-subtle)',
            gap: 12,
          }}>
            <div className="sdh-mono-label">статья</div>
            <div className="sdh-mono-label" style={{ textAlign: 'right' }}>вызовов</div>
            <div className="sdh-mono-label" style={{ textAlign: 'right' }}>средн. стоимость</div>
            <div className="sdh-mono-label" style={{ textAlign: 'right' }}>итого</div>
          </div>
          {items.map((i, idx) => (
            <div key={idx} style={{
              display: 'grid', gridTemplateColumns: '1fr 140px 140px 120px',
              padding: '14px 20px',
              gap: 12,
              alignItems: 'center',
              borderBottom: idx === items.length - 1 ? 'none' : '1px solid var(--border-subtle)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <CategoryPill hue={i.hue} small>·</CategoryPill>
                <span style={{ fontSize: 14, color: 'var(--text-primary)' }}>{i.label}</span>
              </div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-secondary)' }}>
                {i.calls.toLocaleString('ru-RU')}
              </div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-tertiary)' }}>
                ${(i.usd / i.calls * 1000).toFixed(2)}/1k
              </div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 500, color: 'var(--text-primary)' }}>
                ${i.usd.toFixed(2)}
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

window.MarketSection = MarketSection;
window.MethodologiesSection = MethodologiesSection;
window.CostsPage = CostsPage;
