// Scene 3: Scrivener — Document Generation (22–28s, 6s)
// Rebuilt with springs, cadenced typing, staggered section reveal,
// word-count counters, NetDocuments row pulse.

function SceneScrivener() {
  const { localTime } = useSprite();
  const t = localTime;

  const cursorPath = [
    { t: 0.0, x: 960, y: 540 },
    { t: 1.0, x: 960, y: 660 },
    { t: 3.3, x: 1720, y: 130, click: true },
    { t: 4.3, x: 1720, y: 250, click: true },
    { t: 6.0, x: 1720, y: 250 },
  ];
  const cursor = cursorPhysics(cursorPath, t);

  const prompt = "Draft a motion for summary judgment on the breach of contract claim, incorporating the indemnification analysis from the Assistant.";
  const typedPrompt = typewrite(prompt, t, 0.2, 58);
  const submitted = t > 1.55;

  const sections = [
    { title: 'I. Introduction', t: 1.9, words: 12 },
    { title: 'II. Statement of Undisputed Facts', t: 2.2, words: 18 },
    { title: 'III. Legal Standard', t: 2.5, words: 14 },
    { title: 'IV. Argument', t: 2.8, words: 22 },
    { title: '    A. Breach of Contract Elements Are Established', t: 3.0, words: 20 },
    { title: '    B. Indemnification Carve-outs Support Judgment', t: 3.2, words: 24 },
    { title: 'V. Conclusion', t: 3.5, words: 10 },
  ];

  const exportOpen = t > 3.3 && t < 4.6;
  const exporting = t > 4.3;

  const camStops = [
    { t: 0.0, scale: 1.03, x: 960, y: 620 },
    { t: 1.6, scale: 1.0,  x: 960, y: 540 },
    { t: 2.4, scale: 1.04, x: 960, y: 560 },
    { t: 3.6, scale: 1.03, x: 1180, y: 440 },
    { t: 6.0, scale: 1.03, x: 1180, y: 440 },
  ];

  return (
    <Camera stops={camStops}>
      <AewitaShell activeMode="scrivener">
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
          {/* Header */}
          <div style={{
            height: 64, flexShrink: 0,
            borderBottom: `1px solid ${COLORS.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '0 24px',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ fontSize: 20, fontWeight: 600, fontFamily: FONTS.serif }}>Scrivener</div>
              <div style={{
                fontSize: 12, color: COLORS.textMuted,
                opacity: spring(t, 0, 1, 1.5, Springs.snappy),
              }}>
                {submitted ? 'Motion for Summary Judgment · Draft' : 'Describe what you need'}
              </div>
            </div>
            <ExportButton t={t} exportOpen={exportOpen} exporting={exporting} />
          </div>

          {/* Body */}
          <div style={{ flex: 1, overflow: 'hidden', padding: '24px 80px' }}>
            {!submitted ? (
              <PromptView t={t} typedPrompt={typedPrompt} />
            ) : (
              <DraftView t={t} sections={sections} />
            )}
          </div>
        </div>
      </AewitaShell>
      <Cursor x={cursor.x} y={cursor.y} clicking={cursor.clicking} scale={cursor.scale} />
    </Camera>
  );
}

function PromptView({ t, typedPrompt }) {
  const quillP = spring(t, 0, 1, 0, { stiffness: 180, damping: 18 });
  return (
    <div style={{
      maxWidth: 760, margin: '120px auto 0',
      display: 'flex', flexDirection: 'column', gap: 20,
    }}>
      <div style={{ transform: `scale(${Math.min(1.1, quillP)})` }}>
        <AewitaQuill size={44} color="rgba(217,72,78,0.4)" />
      </div>
      <div style={{
        fontFamily: FONTS.serif, fontSize: 28, color: COLORS.textPrimary,
        opacity: spring(t, 0, 1, 0.05, Springs.snappy),
        transform: `translateY(${(1 - spring(t, 0, 1, 0.05, Springs.snappy)) * 8}px)`,
      }}>
        What do you need to draft?
      </div>
      <div style={{
        padding: 16,
        background: COLORS.bgCard,
        border: `1px solid ${typedPrompt ? COLORS.copper : COLORS.border}`,
        borderRadius: 12,
        fontSize: 14, color: COLORS.textPrimary,
        minHeight: 60,
        boxShadow: typedPrompt ? `0 0 ${18 + 6 * Math.sin(t * 5)}px rgba(217,72,78,0.1)` : 'none',
      }}>
        {typedPrompt || <span style={{ color: COLORS.textMuted }}>e.g. "Draft a motion for summary judgment…"</span>}
        {typedPrompt && typedPrompt.length < 130 && (
          <span style={{
            display: 'inline-block', width: 1.5, height: 16,
            background: COLORS.copper, marginLeft: 2,
            verticalAlign: 'middle',
            opacity: Math.sin(t * 8) > 0 ? 1 : 0,
          }}/>
        )}
      </div>
    </div>
  );
}

function DraftView({ t, sections }) {
  const containerP = spring(t, 0, 1, 1.55, { stiffness: 180, damping: 22 });
  return (
    <div style={{
      maxWidth: 820, margin: '0 auto',
      padding: '32px 48px',
      background: COLORS.bgRaised,
      border: `1px solid ${COLORS.border}`,
      borderRadius: 12,
      opacity: Math.min(1, containerP),
      transform: `translateY(${(1 - Math.min(1, containerP)) * 20}px)`,
    }}>
      <div style={{
        fontFamily: FONTS.serif, fontSize: 22, fontWeight: 700,
        color: COLORS.textPrimary, textAlign: 'center', marginBottom: 6,
        opacity: spring(t, 0, 1, 1.7, Springs.snappy),
      }}>
        MOTION FOR SUMMARY JUDGMENT
      </div>
      <div style={{
        fontFamily: FONTS.mono, fontSize: 10,
        color: COLORS.textMuted, textAlign: 'center', letterSpacing: '0.08em',
        textTransform: 'uppercase', marginBottom: 28,
        opacity: spring(t, 0, 1, 1.78, Springs.snappy),
      }}>
        Reeves v. Meridian Health Systems · No. 23-CV-4421 · N.D. Tex.
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {sections.map((s, i) => {
          const enterP = spring(t, 0, 1, s.t, { stiffness: 260, damping: 22 });
          const complete = t > s.t + 0.6;
          const indent = s.title.startsWith('    ') ? 24 : 0;
          // Counter: word count springs up from 0 to target when complete
          const wordC = complete
            ? Math.round(countUp(t, 0, s.words, s.t + 0.6, { stiffness: 100, damping: 24 }))
            : 0;
          return (
            <div key={i} style={{
              opacity: Math.min(1, enterP),
              display: 'flex', alignItems: 'center', gap: 12,
              paddingLeft: indent,
              transform: `translateX(${(1 - Math.min(1, enterP)) * -12}px)`,
            }}>
              <div style={{
                width: 10, height: 10, borderRadius: 5,
                background: complete ? COLORS.sage : COLORS.copper,
                flexShrink: 0,
                boxShadow: complete ? 'none' : `0 0 ${10 + 4 * Math.sin(t * 6)}px ${COLORS.copper}`,
                transform: `scale(${complete ? 0.85 + 0.15 * Math.min(1, spring(t, 0, 1, s.t + 0.6, Springs.bouncy)) : 1})`,
              }}/>
              <div style={{
                flex: 1,
                fontFamily: FONTS.serif, fontSize: 15,
                color: COLORS.textPrimary, fontWeight: 500,
              }}>{s.title.trim()}</div>
              <div style={{ fontSize: 10, fontFamily: FONTS.mono, color: COLORS.textMuted, minWidth: 110, textAlign: 'right' }}>
                {complete ? `${wordC} ¶ · Bluebook cites` : 'drafting…'}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ExportButton({ t, exportOpen, exporting }) {
  const btnP = spring(t, 1, 0.96, 3.3, { stiffness: 300, damping: 16 });
  const clickSquash = t >= 3.3 && t < 3.5 ? 0.96 + 0.04 * ((t - 3.3) / 0.2) : 1;
  return (
    <div style={{ position: 'relative' }}>
      <div style={{
        padding: '8px 16px',
        background: exporting ? COLORS.accent : COLORS.copperDim,
        border: `1px solid ${exporting ? COLORS.accent : COLORS.copper}`,
        borderRadius: 8,
        fontSize: 13, fontWeight: 500,
        color: COLORS.textPrimary,
        display: 'flex', alignItems: 'center', gap: 8,
        transform: `scale(${clickSquash})`,
      }}>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
          <path d="M6 1v7M3 5l3 3 3-3M2 11h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        Export
      </div>

      {exportOpen && (
        <ExportMenu t={t} />
      )}
    </div>
  );
}

function ExportMenu({ t }) {
  const formats = ['PDF', 'DOCX', 'NetDocuments', 'iManage'];
  const openP = spring(t, 0, 1, 3.35, { stiffness: 300, damping: 22 });
  return (
    <div style={{
      position: 'absolute', top: 'calc(100% + 6px)', right: 0,
      width: 220,
      background: COLORS.bgCard,
      border: `1px solid ${COLORS.borderStrong}`,
      borderRadius: 10,
      boxShadow: `0 20px 40px rgba(0,0,0,${0.5 * Math.min(1, openP)})`,
      padding: 4,
      zIndex: 10,
      opacity: Math.min(1, openP),
      transform: `translateY(${(1 - Math.min(1, openP)) * -8}px) scale(${0.94 + 0.06 * Math.min(1, openP)})`,
      transformOrigin: 'top right',
    }}>
      {formats.map((fmt, i) => {
        const itemP = stagger(t, i, 0.04, 3.4, { stiffness: 260, damping: 22 });
        const highlighted = fmt === 'NetDocuments' && t > 4.25;
        const pulseStrength = highlighted ? 0.5 + 0.5 * Math.sin((t - 4.25) * 8) : 0;
        return (
          <div key={fmt} style={{
            padding: '10px 12px', borderRadius: 6,
            fontSize: 13,
            color: highlighted ? COLORS.accent : COLORS.textPrimary,
            background: highlighted
              ? `rgba(217,72,78,${0.10 + 0.08 * pulseStrength})`
              : 'transparent',
            opacity: Math.min(1, itemP),
            transform: `translateY(${(1 - Math.min(1, itemP)) * 4}px)`,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <span>{fmt}</span>
            {fmt === 'NetDocuments' && (
              <span style={{
                fontSize: 10, fontFamily: FONTS.mono,
                color: highlighted ? COLORS.copper : COLORS.textMuted,
              }}>sync</span>
            )}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { SceneScrivener });
