// Scene 1: Library — Document Intelligence (0–10s)
// Motion system: springs everywhere, staggered grid reveal, cadenced typing,
// cursor physics with click squash, matter dropdown springs open.

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

  // ── Cursor physics path ──────────────────────────────────────────────
  const cursorPath = [
    { t: 0.0, x: 1000, y: 700 },
    { t: 1.4, x: 1680, y: 115 },
    { t: 1.8, x: 1680, y: 115, click: true },          // open dropdown
    { t: 3.0, x: 1680, y: 260 },
    { t: 3.3, x: 1680, y: 260, click: true },          // select matter
    { t: 5.2, x: 900, y: 320 },                         // drag source
    { t: 5.8, x: 900, y: 320, click: true },
    { t: 6.6, x: 900, y: 240 },                         // release on upload zone
    { t: 7.4, x: 320, y: 170 },                         // Query tab
    { t: 7.8, x: 320, y: 170, click: true },
    { t: 8.4, x: 960, y: 830 },                         // input bar
    { t: 9.2, x: 960, y: 830, click: true },            // enter
    { t: 10.0, x: 960, y: 830 },
  ];
  const cursor = cursorPhysics(cursorPath, t);

  // ── State flags driven by time ───────────────────────────────────────
  const matterOpen = t > 1.8 && t < 3.3;
  const matterSelected = t > 3.3;
  const uploadVisible = t > 5.5 && t < 7.3;
  const queryTabActive = t > 7.8;

  // Upload progress — spring, not linear
  const uploadProg = clampN(spring(t, 0, 1, 5.9, { stiffness: 50, damping: 24, mass: 1 }), 0, 1);

  // Cadenced typing
  const queryText = typewrite(
    "What are the indemnification carve-outs across all vendor agreements?",
    t, 8.05, 38
  );

  // Camera — gentle parallax-friendly stops
  const cameraStops = [
    { t: 0.0, scale: 1.05, x: 560, y: 480 },        // slight push on whole UI
    { t: 1.0, scale: 1.0,  x: 960, y: 540 },
    { t: 1.8, scale: 1.03, x: 1240, y: 440 },       // lean toward matter dropdown
    { t: 3.5, scale: 1.0,  x: 960, y: 540 },
    { t: 5.5, scale: 1.04, x: 960, y: 440 },        // upload zone
    { t: 7.2, scale: 1.0,  x: 960, y: 540 },
    { t: 8.0, scale: 1.03, x: 960, y: 620 },
    { t: 10.0, scale: 1.03, x: 960, y: 620 },
  ];

  // Parallax layers: sidebar moves slightly less than content during camera pushes
  return (
    <Camera stops={cameraStops}>
      <AewitaShell activeMode="library" pulseLogo={t < 1.2} time={t}>
        <LibraryContent
          t={t}
          matterOpen={matterOpen}
          matterSelected={matterSelected}
          uploadVisible={uploadVisible}
          uploadProg={uploadProg}
          queryTabActive={queryTabActive}
          queryText={queryText}
        />
      </AewitaShell>
      <Cursor x={cursor.x} y={cursor.y} clicking={cursor.clicking} scale={cursor.scale} />
    </Camera>
  );
}

function LibraryContent({ t, matterOpen, matterSelected, uploadVisible, uploadProg, queryTabActive, queryText }) {
  const matters = [
    { name: 'Reeves v. Meridian Health Systems', meta: 'Litigation · TX' },
    { name: 'Phantom Interactive / ClutchCast',  meta: 'M&A · DE' },
    { name: 'Cedar Ridge Acquisition',            meta: 'Real Estate · CA' },
    { name: 'Halden Robotics Series C',           meta: 'Corporate · NY' },
  ];
  const docs = [
    { name: 'Master Services Agreement — v7.docx', size: '248 KB', time: '2h ago', type: 'contract' },
    { name: 'Vendor Addendum — Meridian.pdf',      size: '1.2 MB', time: '4h ago', type: 'contract' },
    { name: 'Deposition — Dr. Reeves.pdf',         size: '3.4 MB', time: 'yesterday', type: 'discovery' },
    { name: 'Motion in Limine — Draft 3.docx',     size: '189 KB', time: 'yesterday', type: 'brief' },
    { name: 'Expert Report — Lindeman.pdf',        size: '2.7 MB', time: '2d ago', type: 'discovery' },
    { name: 'Indemnification Analysis Memo.md',    size: '34 KB', time: '2d ago', type: 'brief' },
    { name: 'Privilege Log — Revised.xlsx',        size: '87 KB', time: '3d ago', type: 'discovery' },
    { name: 'Supplier Agreement — Kestrel.pdf',    size: '892 KB', time: '3d ago', type: 'contract' },
    { name: 'Correspondence — Opposing Counsel.pdf', size: '1.8 MB', time: '4d ago', type: 'discovery' },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column' }}>
      {/* Top bar */}
      <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={{ color: COLORS.copper }}>{Icons.folder}</div>
          <div style={{ fontSize: 20, fontWeight: 600, fontFamily: FONTS.serif }}>Library</div>
          <div style={{ fontSize: 12, color: COLORS.textMuted,
                        opacity: spring(t, 0, 1, 3.5, Springs.gentle) }}>
            {matterSelected ? `${docs.length} documents` : '0 documents'}
          </div>
        </div>

        {/* Matter selector */}
        <MatterSelector
          matters={matters}
          t={t}
          open={matterOpen}
          selected={matterSelected}
        />
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, padding: '12px 24px 0', borderBottom: `1px solid ${COLORS.border}` }}>
        <Tab label="Library" icon={Icons.library} active={!queryTabActive} />
        <Tab label="Query" icon={Icons.chat} active={queryTabActive} />
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflow: 'hidden', padding: 24, position: 'relative' }}>
        {!queryTabActive && (
          <>
            <UploadZone t={t} visible={uploadVisible} progress={uploadProg} matterSelected={matterSelected} />

            {/* Search/filter */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 14px',
              background: COLORS.bgSunken,
              border: `1px solid ${COLORS.border}`,
              borderRadius: 8, marginBottom: 16,
              opacity: spring(t, 0, 1, 3.8, Springs.gentle),
            }}>
              <div style={{ color: COLORS.textMuted }}>{Icons.search}</div>
              <div style={{ fontSize: 13, color: COLORS.textMuted }}>Filter by file name, type, date…</div>
            </div>

            {/* Docs grid */}
            {!matterSelected ? (
              <div style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                padding: '60px 20px', color: COLORS.textMuted, gap: 10,
                opacity: Math.max(0, 1 - spring(t, 0, 1, 3.2, Springs.snappy)),
              }}>
                <div style={{ opacity: 0.4 }}>{Icons.doc}</div>
                <div style={{ fontSize: 14, color: COLORS.textSecondary, fontWeight: 500 }}>No documents yet</div>
                <div style={{ fontSize: 12 }}>Select a matter to see its documents</div>
              </div>
            ) : (
              <DocGrid docs={docs} t={t} />
            )}
          </>
        )}

        {queryTabActive && <QueryPanel t={t} queryText={queryText} />}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Matter selector — springs the dropdown open, staggers items in,
// highlights the selected one with a spring.
// ──────────────────────────────────────────────────────────────────────
function MatterSelector({ matters, t, open, selected }) {
  // Spring-based open/close: controls height, opacity, y-offset of dropdown
  // When open starts at 1.8, we spring to 1. When it ends at 3.3, we spring back to 0.
  const openP = open
    ? clampN(spring(t, 0, 1, 1.8, { stiffness: 320, damping: 22 }), 0, 1.1)
    : (t > 3.3 ? Math.max(0, 1 - spring(t, 0, 1, 3.3, { stiffness: 400, damping: 30 })) : 0);

  // Visual squish when user clicks the trigger
  const clickSquash = t >= 1.8 && t < 1.95
    ? 1 - 0.03 * Math.sin((t - 1.8) / 0.15 * Math.PI)
    : 1;

  return (
    <div style={{ position: 'relative' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '8px 14px',
        background: COLORS.bgCard,
        border: `1px solid ${open || selected ? COLORS.copper : COLORS.border}`,
        borderRadius: 8, fontSize: 13, color: COLORS.textPrimary,
        minWidth: 260, justifyContent: 'space-between',
        transform: `scale(${clickSquash})`,
        transition: 'border-color 140ms',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {Icons.brief}
          <span style={{ color: selected ? COLORS.textPrimary : COLORS.textSecondary }}>
            {selected ? 'Reeves v. Meridian Health' : 'Select Matter'}
          </span>
        </div>
        <div style={{
          transform: `rotate(${openP * 180}deg)`,
          color: COLORS.textSecondary,
        }}>{Icons.chevron}</div>
      </div>

      {openP > 0.01 && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0,
          width: 320,
          background: COLORS.bgCard,
          border: `1px solid ${COLORS.borderStrong}`,
          borderRadius: 10,
          boxShadow: `0 ${20 * openP}px ${40 * openP}px rgba(0,0,0,${0.5 * openP})`,
          padding: 6,
          zIndex: 10,
          opacity: Math.min(1, openP),
          transform: `translateY(${(1 - openP) * -8}px) scale(${0.95 + 0.05 * openP})`,
          transformOrigin: 'top right',
        }}>
          {matters.map((m, i) => {
            const itemP = stagger(t, i, 0.055, 1.85, { stiffness: 300, damping: 22 });
            const selecting = t > 3.15 && t < 3.55 && i === 0;
            // Selection ripple: background color pulses copper, shrinks to selected row
            return (
              <div key={m.name} style={{
                padding: '10px 12px', borderRadius: 6,
                opacity: Math.min(1, itemP),
                transform: `translateX(${(1 - itemP) * 10}px)`,
                background: selecting ? `rgba(217,72,78,${0.10 + 0.06 * Math.sin((t - 3.2) * 20)})` : 'transparent',
                fontSize: 13,
              }}>
                <div style={{ color: COLORS.textPrimary, fontWeight: 500 }}>{m.name}</div>
                <div style={{ fontSize: 11, color: COLORS.textMuted, marginTop: 2 }}>{m.meta}</div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Doc grid — staggered spring reveal, each card scales+fades+lifts from y:24
// ──────────────────────────────────────────────────────────────────────
function DocGrid({ docs, t }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
      {docs.map((d, i) => {
        // Stagger: each card starts its spring 45ms after the previous
        const p = stagger(t, i, 0.045, 3.45, { stiffness: 180, damping: 20, mass: 1 });
        const op = clampN(p, 0, 1);
        const ty = (1 - clampN(p, 0, 1)) * 28;
        const sc = 0.92 + 0.08 * clampN(p, 0, 1);
        return (
          <div key={d.name} style={{
            padding: 14,
            background: COLORS.bgCard,
            border: `1px solid ${COLORS.border}`,
            borderRadius: 10,
            opacity: op,
            transform: `translateY(${ty}px) scale(${sc})`,
            transformOrigin: 'center bottom',
            willChange: 'transform',
            display: 'flex', flexDirection: 'column', gap: 8,
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
              <div style={{
                width: 32, height: 32, borderRadius: 6,
                background: d.type === 'contract' ? 'rgba(200,133,107,0.15)'
                         : d.type === 'brief'    ? 'rgba(120,179,124,0.15)'
                         : 'rgba(232,224,216,0.08)',
                color: d.type === 'contract' ? COLORS.copper
                     : d.type === 'brief'    ? COLORS.sage
                     : COLORS.textSecondary,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>{Icons.doc}</div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{
                  fontSize: 12.5, color: COLORS.textPrimary, fontWeight: 500, lineHeight: 1.3,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                }}>{d.name}</div>
                <div style={{ fontSize: 10.5, color: COLORS.textMuted, marginTop: 3, fontFamily: FONTS.mono }}>
                  {d.size} · {d.time}
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Upload zone — dashed border pulses as file lands; progress bar springs.
// ──────────────────────────────────────────────────────────────────────
function UploadZone({ t, visible, progress, matterSelected }) {
  const borderPulse = visible
    ? 1 - 0.3 * Math.exp(-(t - 5.5) * 6) * Math.cos((t - 5.5) * 18)
    : 1;
  return (
    <div style={{
      border: `1.5px dashed ${visible ? COLORS.accent : COLORS.borderStrong}`,
      borderRadius: 10,
      padding: '28px 24px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
      background: visible ? `rgba(217,72,78,${0.04 * borderPulse})` : 'transparent',
      marginBottom: 20,
      transform: `scale(${visible ? 0.995 + 0.005 * Math.sin((t - 5.5) * 8) : 1})`,
    }}>
      <div style={{ color: COLORS.textSecondary }}>{Icons.upload}</div>
      <div style={{ fontSize: 14, color: COLORS.textPrimary, fontWeight: 500 }}>
        {visible ? 'Uploading Expert_Report_Lindeman.pdf' : 'Drag and drop files or folders'}
      </div>
      {!visible ? (
        <>
          <div style={{ fontSize: 12, color: COLORS.textMuted }}>
            {matterSelected ? 'Files will be indexed and linked to this matter' : 'Select a matter first to enable uploads'}
          </div>
          <button style={{
            marginTop: 6, padding: '8px 20px',
            background: COLORS.copperDim, border: `1px solid ${COLORS.copper}`,
            borderRadius: 7, color: COLORS.textPrimary,
            fontSize: 13, fontWeight: 500, fontFamily: FONTS.sans,
          }}>Browse</button>
        </>
      ) : (
        <div style={{ width: 420, marginTop: 6 }}>
          <div style={{ height: 6, borderRadius: 3, background: 'rgba(232,224,216,0.08)', overflow: 'hidden' }}>
            <div style={{
              height: '100%', width: `${progress * 100}%`,
              background: `linear-gradient(90deg, ${COLORS.accent}, #E86B70)`,
              boxShadow: `0 0 ${12 + 8 * Math.sin(t * 6)}px rgba(217,72,78,0.55)`,
            }} />
          </div>
          <div style={{
            fontFamily: FONTS.mono, fontSize: 11, color: COLORS.textMuted,
            marginTop: 6, display: 'flex', justifyContent: 'space-between',
          }}>
            <span>{Math.round(progress * 2700)} KB / 2.7 MB</span>
            <span>{Math.round(progress * 100)}%</span>
          </div>
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────
// Query panel — quill scales in on tab switch, input border pulses on focus,
// caret blinks, typed text appears with cadence.
// ──────────────────────────────────────────────────────────────────────
function QueryPanel({ t, queryText }) {
  const quillScale = spring(t, 0.6, 1, 7.8, { stiffness: 180, damping: 18 });
  const sendArmed = queryText.length > 50;
  const sendPulse = sendArmed ? 0.9 + 0.1 * Math.sin((t - 9) * 6) : 1;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        color: COLORS.textMuted, gap: 10,
      }}>
        <div style={{ transform: `scale(${quillScale})`, transformOrigin: 'center' }}>
          <AewitaQuill size={40} color="rgba(217,72,78,0.3)" />
        </div>
        <div style={{
          fontFamily: FONTS.serif, fontSize: 22, color: COLORS.textPrimary, marginTop: 8,
          opacity: spring(t, 0, 1, 7.9, Springs.snappy),
          transform: `translateY(${(1 - spring(t, 0, 1, 7.9, Springs.snappy)) * 8}px)`,
        }}>
          Query your library
        </div>
        <div style={{
          fontSize: 13, color: COLORS.textSecondary,
          opacity: spring(t, 0, 1, 8.0, Springs.snappy),
        }}>
          Ask a question across every document in this matter.
        </div>
      </div>

      <div style={{
        margin: '0 60px 20px', padding: 14,
        background: COLORS.bgCard,
        border: `1px solid ${queryText ? COLORS.copper : COLORS.border}`,
        borderRadius: 12,
        display: 'flex', alignItems: 'center', gap: 12,
        boxShadow: queryText ? `0 0 ${20 + 8 * Math.sin(t * 4)}px rgba(217,72,78,0.12)` : 'none',
      }}>
        <div style={{ flex: 1, fontSize: 14, color: COLORS.textPrimary, minHeight: 20 }}>
          {queryText}
          {queryText && queryText.length < 77 && (
            <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,
            }}/>
          )}
          {!queryText && <span style={{ color: COLORS.textMuted }}>Ask about your documents…</span>}
        </div>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: sendArmed ? COLORS.accent : 'rgba(232,224,216,0.08)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: sendArmed ? '#fff' : COLORS.textMuted,
          transform: `scale(${sendPulse})`,
          boxShadow: sendArmed ? `0 0 20px rgba(217,72,78,0.4)` : 'none',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M7 2v10M3 6l4-4 4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

function Tab({ label, icon, active }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '10px 16px',
      borderBottom: active ? `2px solid ${COLORS.accent}` : '2px solid transparent',
      color: active ? COLORS.textPrimary : COLORS.textMuted,
      fontSize: 13, fontWeight: active ? 600 : 400, marginBottom: -1,
    }}>
      <div style={{ color: active ? COLORS.accent : COLORS.textMuted }}>{icon}</div>
      {label}
    </div>
  );
}

Object.assign(window, { SceneLibrary });
