// ════════════════════════════════════════════════════════════════
// IdeaGrid — 43 идеи Стартапзавода + IdeaCard + IdeaExpansion
// ════════════════════════════════════════════════════════════════
const { useState: useStateIdea } = React;

function IdeaGrid({ onOpenSynthesis }) {
  const D = window.SDH_DATA;
  const [family, setFamily] = useStateIdea('all');
  const [focusOnly, setFocusOnly] = useStateIdea(false);
  const [open, setOpen] = useStateIdea(null);

  let arr = D.ideas;
  if (family !== 'all') arr = arr.filter(i => i.family === family);
  if (focusOnly) arr = arr.filter(i => i.focus);

  const focusCount = D.ideas.filter(i => i.focus).length;

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

      {/* FILTER */}
      <CommandBar
        left={
          <>
            <span className="sdh-mono-label" style={{ marginRight: 6 }}>семья</span>
            <button className={`sdh-chip ${family === 'all' ? 'is-active' : ''}`} onClick={() => setFamily('all')}>
              все <span className="chip-count">{D.ideas.length}</span>
            </button>
            {D.FAMILIES.map(f => {
              const count = D.ideas.filter(i => i.family === f.id).length;
              return (
                <button key={f.id} className={`sdh-chip ${family === f.id ? 'is-active' : ''}`} onClick={() => setFamily(f.id)}>
                  {f.label2 || f.label} <span className="chip-count">{count}</span>
                </button>
              );
            })}
          </>
        }
        right={
          <button className={`sdh-chip ${focusOnly ? 'is-active' : ''}`} onClick={() => setFocusOnly(v => !v)}>
            <span style={{ color: 'var(--brand-bronze)' }}>★</span> только в фокусе <span className="chip-count">{focusCount}</span>
          </button>
        }
      />

      {/* GRID */}
      <section className="sdh-container" style={{ paddingTop: 'var(--space-6)', paddingBottom: 'var(--space-16)' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
          gap: 'var(--space-4)',
        }}>
          {arr.map(idea => (
            <IdeaCard key={idea.number} idea={idea} onOpen={() => setOpen(idea)} />
          ))}
        </div>
      </section>

      {open && <IdeaExpansion idea={open} onClose={() => setOpen(null)}
        onOpenSynthesis={() => { const o = open; setOpen(null); onOpenSynthesis && onOpenSynthesis(o); }} />}
    </div>
  );
}

function IdeaCard({ idea, onOpen }) {
  return (
    <div className="sdh-warm-card" style={{
      '--bg-tint': `var(--hue-${idea.familyHue}-subtle)`,
      padding: 'var(--space-4) var(--space-6) var(--space-4)',
      cursor: 'pointer',
      display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
    }} onClick={onOpen}>
      {/* head: number + focus star */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)' }}>
          № {String(idea.number).padStart(2, '0')}
        </span>
        {idea.focus && (
          <span className="sdh-focus-star">★ <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>фокус</span></span>
        )}
      </div>

      {/* title */}
      <h3 style={{
        margin: 0, fontSize: 15.5, fontWeight: 600, color: 'var(--text-primary)',
        lineHeight: 1.3, letterSpacing: '-0.01em',
      }}>{idea.title}</h3>

      {/* badges */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        <CategoryPill hue={idea.familyHue} small>{idea.familyLabel}</CategoryPill>
        <CategoryPill hue={idea.nicheHue} small>{idea.nicheLabel}</CategoryPill>
      </div>

      {/* footer: competitors + beeswarm */}
      <div style={{
        marginTop: 'auto',
        paddingTop: 'var(--space-3)',
        borderTop: '1px solid var(--border-subtle)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
      }}>
        <div className="sdh-mono-label">
          <span style={{ color: 'var(--text-primary)', fontSize: 12 }}>{idea.competitors}</span> конкурентов
          {' · '}
          <span style={{ color: 'var(--text-primary)', fontSize: 12 }}>{idea.linked}</span> связей
        </div>
      </div>
      {idea.competitors >= 3 && (
        <div>
          <div className="sdh-mono-label" style={{ marginBottom: 4 }}>вердикты: рискованно · валидация · жизнеспособно</div>
          <CompetitorBeeswarm verdicts={idea.verdicts} width={260} height={32} />
        </div>
      )}
    </div>
  );
}

function IdeaExpansion({ idea, onClose, onOpenSynthesis }) {
  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-12) 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: 920, width: '100%',
        padding: 'var(--space-8)',
        boxShadow: 'var(--shadow-xl)',
        position: 'relative',
      }}>
        <button className="sdh-btn sdh-btn--ghost" onClick={onClose}
          style={{ position: 'absolute', top: 12, right: 12, padding: 6 }}>
          <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>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 'var(--space-3)' }}>
          <span className="sdh-mono-label">идея № {String(idea.number).padStart(2, '0')}</span>
          {idea.focus && <span className="sdh-focus-star">★ в фокусе</span>}
        </div>

        <h2 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--text-primary)' }}>
          {idea.title}
        </h2>

        <div style={{ display: 'flex', gap: 8, marginTop: 'var(--space-4)' }}>
          <CategoryPill hue={idea.familyHue}>{idea.familyLabel}</CategoryPill>
          <CategoryPill hue={idea.nicheHue}>{idea.nicheLabel}</CategoryPill>
        </div>

        <div style={{
          marginTop: 'var(--space-8)',
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-8)',
        }}>
          {/* LEFT */}
          <div>
            <h4 className="sdh-section-label">
              <InfoLabel {...window.METRIC_DICT.competitors}>конкурентный ландшафт</InfoLabel>
            </h4>
            <div style={{ marginBottom: 'var(--space-4)' }}>
              <CompetitorBeeswarm verdicts={idea.verdicts} width={400} height={42} />
            </div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <Verdict hue="rose" count={idea.verdicts.risky} label="рискованно" />
              <Verdict hue="amber" count={idea.verdicts.validate} label="требует валидации" />
              <Verdict hue="emerald" count={idea.verdicts.viable} label="жизнеспособно" />
            </ul>
          </div>
          {/* right */}
          <div>
            <h4 className="sdh-section-label">
              <InfoLabel {...window.METRIC_DICT.similarity}>близость к идее (релевантность)</InfoLabel>
            </h4>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 'var(--space-4)' }}>
              <MicroSimDot value={idea.similarity} width={180} height={12} />
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--text-primary)' }}>
                {idea.similarity.toFixed(2)}
              </span>
            </div>
            <h4 className="sdh-section-label">
              <InfoLabel {...window.METRIC_DICT.firstSeen}>появилась впервые</InfoLabel>
            </h4>
            <p style={{ margin: 0, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-secondary)' }}>
              {idea.first_seen_at}
            </p>
            <h4 className="sdh-section-label" style={{ margin: 'var(--space-4) 0 var(--space-3)' }}>
              <InfoLabel {...window.METRIC_DICT.linked}>связанные идеи</InfoLabel>
            </h4>
            <p style={{ margin: 0, fontSize: 13, color: 'var(--text-secondary)', marginBottom: 'var(--space-3)' }}>
              <span className="sdh-num" style={{ fontFamily: 'var(--font-mono)', color: 'var(--text-primary)' }}>{idea.linked}</span> прямых пересечений в графе
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {Array.from({ length: idea.linked }).map((_, k) => {
                const seed = idea.number * 11 + k * 7;
                const series = Array.from({ length: 14 }).map((__, t) => ({
                  value: 2 + ((Math.sin((seed + t) * 0.7) + 1) * 4) + ((seed + t * 3) % 5),
                }));
                return (
                  <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--text-tertiary)', width: 28 }}>
                      №{String(((idea.number + k * 3) % 43) + 1).padStart(2, '0')}
                    </span>
                    <IdeaHorizon series={series} width={130} height={14} hue={idea.familyHue} />
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <p className="sdh-quote" style={{
          margin: 'var(--space-8) 0 0',
          padding: 'var(--space-4)',
          borderLeft: '2px solid var(--brand-bronze)',
          background: 'var(--surface-sunken)',
          borderRadius: '0 var(--radius-md) var(--radius-md) 0',
        }}>
          {idea.recommendation}
        </p>

        <div style={{ display: 'flex', gap: 8, marginTop: 'var(--space-6)', justifyContent: 'flex-end' }}>
          <button className="sdh-btn sdh-btn--ghost" onClick={onClose}>Закрыть</button>
          <button className="sdh-btn sdh-btn--bronze" onClick={onOpenSynthesis}>
            Открыть синтез-сессию
            <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>
  );
}

function Verdict({ hue, count, label }) {
  return (
    <li style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: `var(--hue-${hue})` }} />
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--text-primary)', minWidth: 24 }}>{count}</span>
      <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>{label}</span>
    </li>
  );
}

window.IdeaGrid = IdeaGrid;
