/* Matter Protocol — Section 05 "Composer demo" (interactive) */

function ComposerSection() {
  const t = window.matterTokens;
  const P = window.PRIMITIVES;
  const pip = { entry: t.pipEntry, risk: t.pipRisk, rebalance: t.pipRebal, exit: t.pipExit };

  // Stack state — each item: {id, cat, name, params}
  const defaultStack = [
    { id: 's1', cat: 'entry', name: 'emaCross', params: { fast: 12, slow: 26 } },
    { id: 's2', cat: 'risk',  name: 'volTarget', params: { sigma: 0.18, lookback: '30d' } },
    { id: 's3', cat: 'exit',  name: 'trailStop', params: { pct: 4.5, activate: '+2%' } },
  ];
  const [stack, setStack] = React.useState(defaultStack);
  const [strategyName, setStrategyName] = React.useState('untitled-strategy');
  const [hoverDrop, setHoverDrop] = React.useState(false);
  const [dragOverIndex, setDragOverIndex] = React.useState(null);
  const idCounter = React.useRef(100);

  const defaultParams = (name) => ({
    emaCross:         { fast: 12, slow: 26 },
    rsiOversold:      { period: 14, level: 30 },
    fundingFlip:      { venue: 'binance', sign: 'pos' },
    volBreakout:      { sigma: 2.0, lookback: '20d' },
    liquiditySweep:   { window: '5m' },
    basisDivergence:  { theta: 0.005 },
    volTarget:        { sigma: 0.18, lookback: '30d' },
    drawdownCap:      { pct: 8 },
    positionLimit:    { notional: '500k' },
    correlationLock:  { theta: 0.6 },
    kellyFraction:    { f: 0.25 },
    timeRebal:        { cadence: '1d' },
    thresholdRebal:   { drift: 0.05 },
    inverseVolWeight: { window: '14d' },
    riskParity:       {},
    trailStop:        { pct: 4.5, activate: '+2%' },
    takeProfitLadder: { tiers: [3, 6, 12] },
    timeInTrade:      { max: '72h' },
  }[name] || {});

  const addPrimitive = (cat, name) => {
    if (stack.some(s => s.name === name)) return; // de-dupe
    idCounter.current += 1;
    setStack([...stack, { id: 's' + idCounter.current, cat, name, params: defaultParams(name) }]);
  };
  const removeAt = (i) => setStack(stack.filter((_, idx) => idx !== i));
  const move = (i, dir) => {
    const j = i + dir;
    if (j < 0 || j >= stack.length) return;
    const next = [...stack];
    [next[i], next[j]] = [next[j], next[i]];
    setStack(next);
  };
  const resetStack = () => setStack(defaultStack);

  // Drag from palette → drop on stack
  const dragName = React.useRef(null);
  const onPaletteDragStart = (cat, name) => (e) => {
    dragName.current = { cat, name };
    e.dataTransfer.effectAllowed = 'copy';
    try { e.dataTransfer.setData('text/plain', name); } catch (_) { /* noop */ }
  };
  const onDropToStack = (e) => {
    e.preventDefault();
    setHoverDrop(false);
    if (dragName.current) {
      addPrimitive(dragName.current.cat, dragName.current.name);
      dragName.current = null;
    }
  };

  // Reorder via drag inside stack
  const reorderFrom = React.useRef(null);
  const onStackDragStart = (i) => (e) => {
    reorderFrom.current = i;
    e.dataTransfer.effectAllowed = 'move';
    try { e.dataTransfer.setData('text/plain', String(i)); } catch (_) { /* noop */ }
  };
  const onStackDragOver = (i) => (e) => {
    e.preventDefault();
    setDragOverIndex(i);
  };
  const onStackDrop = (i) => (e) => {
    e.preventDefault();
    const from = reorderFrom.current;
    setDragOverIndex(null);
    if (from === null || from === undefined) return;
    if (from === i) return;
    const next = [...stack];
    const [it] = next.splice(from, 1);
    next.splice(i, 0, it);
    setStack(next);
    reorderFrom.current = null;
  };

  // Stats
  const cats = new Set(stack.map(s => s.cat));
  const hasEntry = cats.has('entry');
  const hasExit = cats.has('exit');
  const compiles = stack.length > 0 && hasEntry; // entry required
  const issues = [];
  if (!hasEntry) issues.push('needs at least one entry primitive');
  if (stack.length === 0) issues.push('stack is empty');

  // Code preview
  const fmtParams = (p) => {
    const parts = Object.entries(p).map(([k, v]) => {
      if (typeof v === 'string') return `${k}: '${v}'`;
      if (Array.isArray(v)) return `${k}: [${v.join(', ')}]`;
      return `${k}: ${v}`;
    });
    return parts.length ? `{ ${parts.join(', ')} }` : '';
  };

  return (
    <section id="composer-section" style={{ padding: '120px 80px', background: t.surface, borderTop: `1px solid ${t.line}` }}>
      <div style={{ maxWidth: 1440, margin: '0 auto' }}>
        <SectionHead
          num="05"
          eyebrow="composer · try it"
          title="snap a strategy together — right here."
          sub="drag primitives from the palette into the stack. reorder by dragging. the code panel updates as you compose."
        />

        <div style={{
          marginTop: 48,
          background: t.paper,
          border: `1px solid ${t.line}`,
          borderRadius: 18,
          boxShadow: `0 1px 0 ${t.line}, 0 30px 60px -30px rgba(20,19,15,0.16)`,
          overflow: 'hidden',
        }}>
          {/* Chrome */}
          <div style={{
            padding: '14px 20px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            borderBottom: `1px solid ${t.line}`,
            background: t.bg,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ display: 'flex', gap: 5 }}>
                <span style={{ width: 9, height: 9, borderRadius: '50%', background: t.line3 }} />
                <span style={{ width: 9, height: 9, borderRadius: '50%', background: t.line3 }} />
                <span style={{ width: 9, height: 9, borderRadius: '50%', background: t.line3 }} />
              </div>
              <span style={{
                fontFamily: "'Geist Mono', monospace",
                fontSize: 12, color: t.muted,
              }}>composer ·</span>
              <input
                value={strategyName}
                onChange={(e) => setStrategyName(e.target.value.replace(/\s+/g, '-').toLowerCase())}
                style={{
                  background: 'transparent',
                  border: 'none',
                  outline: 'none',
                  fontFamily: "'Geist Mono', monospace",
                  fontSize: 12,
                  color: t.ink,
                  width: 200,
                  padding: 0,
                  letterSpacing: '-0.005em',
                }}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{
                fontFamily: "'Geist Mono', monospace", fontSize: 10.5,
                textTransform: 'uppercase', letterSpacing: '0.08em',
                color: t.muted,
              }}>{stack.length} primitive{stack.length === 1 ? '' : 's'}</span>
              <button onClick={resetStack} style={{
                background: 'transparent',
                border: `1px solid ${t.line2}`,
                color: t.ink2,
                fontFamily: "'Geist Mono', monospace",
                fontSize: 11,
                padding: '5px 10px',
                borderRadius: 6,
                cursor: 'pointer',
              }}>reset</button>
            </div>
          </div>

          {/* Body */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '260px 1fr 1fr',
            minHeight: 480,
          }}>
            {/* Palette */}
            <div style={{
              borderRight: `1px solid ${t.line}`,
              padding: 16,
              background: t.bg,
              display: 'flex', flexDirection: 'column', gap: 18,
              overflowY: 'auto',
            }}>
              {Object.entries(P).map(([cat, items]) => (
                <div key={cat}>
                  <div style={{
                    fontFamily: "'Geist Mono', monospace",
                    fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.1em',
                    color: t.muted, marginBottom: 8,
                    display: 'flex', alignItems: 'center', gap: 7,
                  }}>
                    <span style={{ width: 7, height: 7, borderRadius: 1.5, background: pip[cat] }} />
                    {cat}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    {items.map(p => {
                      const used = stack.some(s => s.name === p.name);
                      return (
                        <div
                          key={p.name}
                          draggable={!used}
                          onDragStart={onPaletteDragStart(cat, p.name)}
                          onClick={() => !used && addPrimitive(cat, p.name)}
                          style={{
                            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            padding: '7px 10px',
                            fontFamily: "'Geist Mono', monospace",
                            fontSize: 12.5,
                            color: used ? t.soft : t.ink,
                            background: t.paper,
                            border: `1px solid ${t.line}`,
                            borderRadius: 6,
                            cursor: used ? 'not-allowed' : 'grab',
                            letterSpacing: '-0.005em',
                            userSelect: 'none',
                            opacity: used ? 0.55 : 1,
                            transition: 'all 0.12s ease',
                          }}
                          onMouseEnter={(e) => { if (!used) { e.currentTarget.style.borderColor = t.line3; e.currentTarget.style.background = t.surface; } }}
                          onMouseLeave={(e) => { e.currentTarget.style.borderColor = t.line; e.currentTarget.style.background = t.paper; }}
                        >
                          <span style={{ textDecoration: used ? 'line-through' : 'none' }}>{p.name}</span>
                          <span style={{
                            fontSize: 14, color: used ? t.soft : t.muted,
                          }}>{used ? '✓' : '+'}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>

            {/* Stack */}
            <div
              onDragOver={(e) => { if (dragName.current) { e.preventDefault(); setHoverDrop(true); } }}
              onDragLeave={() => setHoverDrop(false)}
              onDrop={onDropToStack}
              style={{
                padding: 20,
                borderRight: `1px solid ${t.line}`,
                background: hoverDrop ? t.limeTint : t.paper,
                display: 'flex', flexDirection: 'column', gap: 8,
                transition: 'background 0.15s ease',
              }}>
              <div style={{
                fontFamily: "'Geist Mono', monospace",
                fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.1em',
                color: t.muted,
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                marginBottom: 4,
              }}>
                <span>strategy stack</span>
                <span style={{ color: t.soft }}>order matters →</span>
              </div>

              {stack.length === 0 && (
                <div style={{
                  flex: 1, minHeight: 200,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: `1.5px dashed ${t.line2}`,
                  borderRadius: 10,
                  color: t.muted,
                  fontFamily: "'Geist Mono', monospace",
                  fontSize: 13,
                }}>drop primitives here</div>
              )}

              {stack.map((s, i) => (
                <div
                  key={s.id}
                  draggable
                  onDragStart={onStackDragStart(i)}
                  onDragOver={onStackDragOver(i)}
                  onDrop={onStackDrop(i)}
                  onDragEnd={() => setDragOverIndex(null)}
                  style={{
                    background: t.paper,
                    border: `1px solid ${dragOverIndex === i ? t.limeDeep : t.line}`,
                    borderRadius: 10,
                    padding: '12px 14px',
                    display: 'flex', flexDirection: 'column', gap: 6,
                    boxShadow: dragOverIndex === i ? `0 0 0 3px ${t.limeWash}` : `0 1px 0 ${t.line}`,
                    cursor: 'grab',
                    position: 'relative',
                  }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                      <span style={{
                        fontFamily: "'Geist Mono', monospace",
                        fontSize: 10.5, color: t.soft, width: 14,
                      }}>{String(i + 1).padStart(2, '0')}</span>
                      <span style={{
                        width: 9, height: 9, borderRadius: 2, background: pip[s.cat],
                      }} />
                      <span style={{
                        fontFamily: "'Geist Mono', monospace",
                        fontSize: 13.5, color: t.ink, letterSpacing: '-0.005em',
                      }}>{s.name}</span>
                      <span style={{
                        fontFamily: "'Geist Mono', monospace",
                        fontSize: 10, color: t.muted,
                        textTransform: 'uppercase', letterSpacing: '0.08em',
                      }}>{s.cat}</span>
                    </div>
                    <div style={{ display: 'flex', gap: 2 }}>
                      <IconBtn label="↑" onClick={() => move(i, -1)} disabled={i === 0} />
                      <IconBtn label="↓" onClick={() => move(i, +1)} disabled={i === stack.length - 1} />
                      <IconBtn label="×" onClick={() => removeAt(i)} />
                    </div>
                  </div>
                  {Object.keys(s.params).length > 0 && (
                    <div style={{
                      fontFamily: "'Geist Mono', monospace",
                      fontSize: 11.5,
                      color: t.muted,
                      paddingLeft: 32,
                    }}>{fmtParams(s.params)}</div>
                  )}
                </div>
              ))}
            </div>

            {/* Code preview */}
            <div style={{
              padding: 0,
              background: t.bg,
              display: 'flex', flexDirection: 'column',
            }}>
              <div style={{
                padding: '14px 20px 10px',
                borderBottom: `1px solid ${t.line}`,
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span style={{
                  fontFamily: "'Geist Mono', monospace",
                  fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.1em',
                  color: t.muted,
                }}>strategy.ts</span>
                <span style={{
                  fontFamily: "'Geist Mono', monospace", fontSize: 10.5, color: t.muted,
                }}>typescript</span>
              </div>
              <div style={{
                padding: '16px 20px',
                fontFamily: "'Geist Mono', monospace",
                fontSize: 12.5,
                lineHeight: 1.7,
                color: t.ink,
                letterSpacing: '-0.005em',
                flex: 1,
                overflowX: 'auto',
              }}>
                <div><span style={{ color: t.muted }}>import</span> {'{ matter }'} <span style={{ color: t.muted }}>from</span> <span style={{ color: t.limeDeep }}>'@matter/sdk'</span></div>
                <div style={{ marginTop: 12 }}>
                  <span style={{ color: t.muted }}>export const</span> <span style={{ color: t.ink }}>{strategyName.replace(/-/g, '_')}</span> <span style={{ color: t.muted }}>=</span> matter.<span style={{ color: t.ink }}>compose</span>([
                </div>
                {stack.map((s, i) => (
                  <div key={s.id} style={{ paddingLeft: 18 }}>
                    <span style={{
                      background: pip[s.cat] === t.pipExit ? 'rgba(20,19,15,0.10)'
                                : pip[s.cat] === t.pipEntry ? 'rgba(168,204,30,0.20)'
                                : pip[s.cat] === t.pipRisk  ? 'rgba(224,122,58,0.16)'
                                : 'rgba(63,143,224,0.14)',
                      padding: '0 3px',
                      borderRadius: 2,
                    }}>{s.name}</span><span style={{ color: t.muted }}>({fmtParams(s.params)}){i < stack.length - 1 ? ',' : ''}</span>
                  </div>
                ))}
                <div><span style={{ color: t.muted }}>])</span></div>
                <div style={{ marginTop: 12 }}>
                  <span style={{ color: t.soft }}>// inferred type:</span>
                </div>
                <div>
                  <span style={{ color: t.muted }}>Strategy&lt;</span>
                  <span style={{ color: t.ink }}>{stack.map(s => s.cat[0].toUpperCase() + s.cat.slice(1)).join(' & ') || 'never'}</span>
                  <span style={{ color: t.muted }}>&gt;</span>
                </div>
              </div>
            </div>
          </div>

          {/* Footer bar */}
          <div style={{
            padding: '12px 20px',
            borderTop: `1px solid ${t.line}`,
            background: t.paper,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <div style={{
              fontFamily: "'Geist Mono', monospace", fontSize: 12,
              color: t.muted, display: 'flex', alignItems: 'center', gap: 16,
            }}>
              <span style={{ color: compiles ? t.ink2 : '#C24F1F' }}>
                <span style={{ color: compiles ? t.limeDeep : '#C24F1F' }}>●</span>{' '}
                {compiles ? 'compiles' : 'won\'t compile'}
              </span>
              {issues.length > 0 ? (
                issues.map((m, i) => <span key={i} style={{ color: '#A05317' }}>· {m}</span>)
              ) : (
                <>
                  <span>· types ok</span>
                  <span>· interfaces match</span>
                </>
              )}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => window.matterUI?.openNotice?.('changelog')} style={{
                background: 'transparent', color: t.ink2, fontSize: 13, fontWeight: 500,
                padding: '8px 14px', borderRadius: 8, border: `1px solid ${t.line2}`,
                letterSpacing: '-0.005em', cursor: 'pointer', fontFamily: 'inherit',
              }}>backtest</button>
              <button
                onClick={() => compiles && window.matterUI?.openAccess?.()}
                disabled={!compiles}
                style={{
                  background: compiles ? t.lime : t.line,
                  color: t.ink, fontSize: 13, fontWeight: 500,
                  padding: '8px 14px', borderRadius: 8, border: 'none',
                  letterSpacing: '-0.005em',
                  cursor: compiles ? 'pointer' : 'not-allowed',
                  opacity: compiles ? 1 : 0.6,
                  fontFamily: 'inherit',
                }}>ship it →</button>
            </div>
          </div>
        </div>

        <div style={{
          marginTop: 16,
          fontFamily: "'Geist Mono', monospace",
          fontSize: 11,
          color: t.soft,
          textAlign: 'center',
        }}>
          a sketch of the real composer. the production sdk is typescript-first and runs locally.
        </div>
      </div>
    </section>
  );
}

function IconBtn({ label, onClick, disabled }) {
  const t = window.matterTokens;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: 24, height: 24,
      background: 'transparent',
      border: `1px solid ${t.line}`,
      borderRadius: 5,
      color: disabled ? t.soft : t.ink2,
      cursor: disabled ? 'not-allowed' : 'pointer',
      fontSize: 12,
      fontFamily: "'Geist Mono', monospace",
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      opacity: disabled ? 0.5 : 1,
      padding: 0,
    }}
    onMouseEnter={(e) => { if (!disabled) e.currentTarget.style.borderColor = t.line3; }}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = t.line}
    >{label}</button>
  );
}

Object.assign(window, { ComposerSection });
