// R2 public dev URL — bucket: arb-cap-dataroom
// v1: public read; will swap for signed URLs once backend is up.
const R2_DECK_BASE = "https://pub-2a559e56ce2048ceb8d21ad7f532e280.r2.dev/deck/latest";

// Telegram handle the "Open private channel" button deeplinks to.
// Tier 1: investor lands in a DM with you, message prefilled with their identity.
// Tier 2.5 plan: see telegram.md
const TELEGRAM_HANDLE = "@jbgib";

// Build a t.me URL with the investor's identity prefilled into the first message.
// Tolerant of "@handle" or "handle" forms in TELEGRAM_HANDLE.
function makeTelegramUrl(identity) {
  const id = identity || {};
  const who = [id.name, id.firm && `(${id.firm})`].filter(Boolean).join(' ');
  const subject = who ? `I'm ${who}` : "I'm looking at your data room";
  const text = `Hi — ${subject}. Looking at the Arb Capital data room and would love to chat.`;
  const handle = TELEGRAM_HANDLE.replace(/^@/, '');
  return `https://t.me/${handle}?text=${encodeURIComponent(text)}`;
}

// File registry — populated from manifest.json on R2 at app boot.
// See loadManifest() in app.jsx. Drafts (visibility !== 'live') are filtered out.
const ROOM_FILES = [];

// Section list — overridable by manifest.sections; defaults if absent.
const DEFAULT_SECTIONS = ['OVERVIEW', 'FINANCIALS', 'ALPHA', 'AUDITS', 'LEGAL', 'LINKS'];
const SECTIONS = [...DEFAULT_SECTIONS];

// Pretty-case label for a section slug ("ALPHA" → "Alpha").
function sectionLabel(s) {
  return s.charAt(0) + s.slice(1).toLowerCase();
}

function Room({ tweaks, identity, returning, onOpenFile, onLogout }) {
  const [activeSection, setActiveSection] = React.useState('ALL');
  const [search, setSearch] = React.useState('');
  const [view, setView] = React.useState('list'); // list | grid

  const filtered = ROOM_FILES.filter(f => {
    if (activeSection !== 'ALL' && f.section !== activeSection) return false;
    if (search && !f.name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const grouped = SECTIONS.map(s => ({
    section: s,
    files: filtered.filter(f => f.section === s),
  })).filter(g => g.files.length > 0);

  return (
    <div className="room-root" style={{ display: 'flex', minHeight: '100vh', background: 'var(--bg)' }}>
      {/* Sidebar */}
      <aside className="room-sidebar" style={{
        width: 240, flexShrink: 0,
        background: 'var(--bg)',
        borderRight: '1px solid var(--border)',
        padding: '20px 0',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '0 20px', marginBottom: 28 }}>
          <ArbWordmark size={11} variant={tweaks.logoVariant} />
        </div>

        <div className="room-section-header" style={{ padding: '0 20px', marginBottom: 8 }}>
          <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--text-tertiary)' }}>
            ROOM
          </div>
        </div>

        <div className="room-section-list">
          <NavItem
            active={activeSection === 'ALL'}
            onClick={() => setActiveSection('ALL')}
            label="All documents"
            count={ROOM_FILES.length}
          />
          {SECTIONS.map((s, i) => {
            const cnt = ROOM_FILES.filter(f => f.section === s).length;
            return (
              <NavItem key={s}
                active={activeSection === s}
                onClick={() => setActiveSection(s)}
                num={i + 1}
                label={s.charAt(0) + s.slice(1).toLowerCase()}
                count={cnt}
              />
            );
          })}
        </div>

        <div className="room-session-block">
          <div style={{ padding: '24px 20px 8px' }}>
            <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--text-tertiary)' }}>
              SESSION
            </div>
          </div>
          <div style={{ padding: '8px 20px', borderTop: '1px solid var(--border)' }}>
            <div style={{ fontSize: 13, marginBottom: 4 }}>{identity.name || identity.email.split('@')[0]}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.06em' }}>
              {identity.firm || identity.email}
            </div>
            <button className="btn btn-ghost btn-sm" style={{ padding: 0, marginTop: 12 }} onClick={onLogout}>
              ↻ Sign out
            </button>
          </div>
        </div>
      </aside>

      {/* Main */}
      <main className="room-main" style={{ flex: 1, padding: '36px 48px', overflow: 'auto', position: 'relative' }}>
        <Watermark email={identity.email} />

        {/* Header */}
        <div className="room-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 32, position: 'relative', zIndex: 10 }}>
          <div>
            <div className="section-num" style={{ marginBottom: 12 }}>
              <span>[ INVESTOR_VIEW ]</span>
              <span className="div" />
              <span>SERIES_SEED · Q2_2026</span>
            </div>
            <h1 style={{ fontSize: 34, letterSpacing: '-0.025em', fontWeight: 400, margin: 0 }}>
              {returning ? 'Welcome back' : 'Welcome'}, {identity.name?.split(' ')[0] || 'investor'}.
            </h1>
            <p style={{ fontSize: 14, color: 'var(--text-secondary)', marginTop: 8, marginBottom: 0 }}>
              {ROOM_FILES.length} {ROOM_FILES.length === 1 ? 'document' : 'documents'}
            </p>
          </div>
          <div className="room-cta-bar" style={{ display: 'flex', gap: 8 }}>
            <a className="btn btn-sm btn-filled" href={makeTelegramUrl(identity)} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>✈ Open private channel</a>
          </div>
        </div>

        {/* Toolbar */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, position: 'relative', zIndex: 10 }}>
          <div style={{ position: 'relative', flex: '0 0 320px' }}>
            <input className="input" style={{ height: 36, fontSize: 13, paddingLeft: 32 }}
              placeholder="Search documents…"
              value={search} onChange={e => setSearch(e.target.value)} />
            <span style={{ position: 'absolute', left: 10, top: 9, color: 'var(--text-tertiary)', fontSize: 14 }}>⌕</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--text-tertiary)' }}>VIEW</span>
            <Segmented value={view} setValue={setView} options={[
              { v: 'list', label: '☰' }, { v: 'grid', label: '▦' }
            ]} />
          </div>
        </div>

        {/* File list */}
        <div style={{ position: 'relative', zIndex: 10 }}>
          {grouped.map(g => (
            <FileSection key={g.section} section={g.section} files={g.files} view={view} onOpen={onOpenFile} />
          ))}
          {grouped.length === 0 && (
            <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-tertiary)', fontSize: 13 }}>
              No documents match.
            </div>
          )}
        </div>
      </main>
    </div>
  );
}

function NavItem({ active, onClick, label, count, num }) {
  return (
    <button onClick={onClick}
      data-active={active ? 'true' : 'false'}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: active ? 'var(--bg-elevated)' : 'transparent',
        border: 'none',
        padding: '10px 20px',
        borderLeft: active ? '2px solid var(--gold)' : '2px solid transparent',
        textAlign: 'left',
        color: active ? 'var(--text-primary)' : 'var(--text-secondary)',
        fontFamily: 'var(--font-sans)',
        fontSize: 13,
        width: '100%',
      }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {num != null && <span className="mono" style={{ fontSize: 9, color: 'var(--text-tertiary)', letterSpacing: '0.08em' }}>[ {String(num).padStart(2,'0')} ]</span>}
        <span>{label}</span>
      </span>
      <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{count}</span>
    </button>
  );
}

function RoomStat({ label, value, delta, pos }) {
  return (
    <Brackets style={{ padding: '14px 16px', background: 'var(--bg-card)', border: '1px solid var(--border)' }}>
      <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--text-tertiary)', marginBottom: 6 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontSize: 22, letterSpacing: '-0.02em' }}>{value}</span>
        {delta && (
          <span className="mono" style={{ fontSize: 10, color: pos ? 'var(--success)' : 'var(--text-tertiary)' }}>
            {pos && '↑ '}{delta}
          </span>
        )}
      </div>
    </Brackets>
  );
}

function Segmented({ value, setValue, options }) {
  return (
    <div style={{ display: 'inline-flex', border: '1px solid var(--border)' }}>
      {options.map(o => (
        <button key={o.v} onClick={() => setValue(o.v)}
          style={{
            padding: '4px 10px', height: 28,
            background: value === o.v ? 'var(--text-primary)' : 'transparent',
            color: value === o.v ? 'var(--bg)' : 'var(--text-secondary)',
            border: 'none',
            fontFamily: 'var(--font-mono)', fontSize: 12,
          }}>{o.label}</button>
      ))}
    </div>
  );
}

function FileSection({ section, files, view, onOpen }) {
  return (
    <section style={{ marginBottom: 32 }}>
      <div className="section-header-row" style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <SectionNum n={SECTIONS.indexOf(section) + 1} label={section} />
        <span style={{ flex: 1, height: 1, background: 'var(--border)' }} />
        <span className="mono section-header-count" style={{ fontSize: 9, color: 'var(--text-tertiary)', letterSpacing: '0.12em' }}>{files.length} {files.length === 1 ? 'DOC' : 'DOCS'}</span>
      </div>

      {view === 'list' ? (
        <div style={{ border: '1px solid var(--border)', background: 'var(--bg-card)' }}>
          {files.map((f, i) => (
            <FileRow key={f.id} file={f} onClick={() => onOpen(f.id)}
              last={i === files.length - 1} />
          ))}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 12 }}>
          {files.map(f => (
            <FileTile key={f.id} file={f} onClick={() => onOpen(f.id)} />
          ))}
        </div>
      )}
    </section>
  );
}

function FileRow({ file, onClick, last }) {
  return (
    <button onClick={onClick}
      className="file-row"
      style={{
        display: 'grid',
        gridTemplateColumns: '40px 1fr 90px 80px 100px 24px',
        alignItems: 'center',
        gap: 16,
        width: '100%',
        padding: '14px 18px',
        background: 'transparent',
        border: 'none',
        borderBottom: last ? 'none' : '1px solid var(--border)',
        textAlign: 'left',
        cursor: 'default',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elevated)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <FileIcon kind={file.kind} />
      <div className="file-row-title" style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, marginBottom: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {file.title || file.name}
        </div>
        <div className="mono file-row-meta" style={{ fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.04em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {file.description}
        </div>
      </div>
      <span className={`badge file-row-badge b-${file.badge === 'CLEARED' || file.badge === 'IMMUTABLE' ? 'success' : file.badge === 'DRAFT' ? 'warning' : file.badge === 'PRIMARY' ? 'gold' : 'default'}`}>
        {file.badge}
      </span>
      <span className="mono file-row-size" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{file.size}</span>
      <span className="mono file-row-date" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{file.updated}</span>
      <span style={{ color: 'var(--text-tertiary)', fontSize: 14 }}>{file.external ? '↗' : '→'}</span>
    </button>
  );
}

function FileTile({ file, onClick }) {
  return (
    <button onClick={onClick}
      style={{
        position: 'relative',
        padding: 18,
        background: 'var(--bg-card)',
        border: '1px solid var(--border)',
        textAlign: 'left',
        height: 180,
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        cursor: 'default',
      }}
      onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--text-primary)'}
      onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}>
      <div>
        <FileIcon kind={file.kind} size={32} />
        <div style={{ fontSize: 14, marginTop: 16, lineHeight: 1.3 }}>{file.title || file.name}</div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>
          {file.size} · {file.pages}p
        </div>
        <span className={`badge b-${file.badge === 'CLEARED' || file.badge === 'IMMUTABLE' ? 'success' : file.badge === 'DRAFT' ? 'warning' : file.badge === 'PRIMARY' ? 'gold' : 'default'}`}>
          {file.badge}
        </span>
      </div>
    </button>
  );
}

Object.assign(window, { Room, ROOM_FILES, SECTIONS, R2_DECK_BASE });
