// screens2.jsx — DebtLift remaining screens (Docs, Profile, Settlement sheet)
// v1.1.0 — production data wiring

// ─────────────────────────────────────────────────────────────
// DOCUMENTS SCREEN
// ─────────────────────────────────────────────────────────────
function DocsScreen({ theme }) {
  const [q, setQ] = React.useState('');
  const files = DL_DATA.files.filter(f => !q || f.name.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="scroll" style={{ height: '100%', overflowY: 'auto', background: theme.canvas, paddingBottom: 110 }}>
      <div style={{ padding: '54px 20px 8px' }}>
        <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 500, letterSpacing: 1.6, textTransform: 'uppercase' }}>Vault</div>
        <h1 className="serif" style={{ fontSize: 32, fontWeight: 400, color: theme.ink, lineHeight: 1, marginTop: 8, letterSpacing: -0.5 }}>
          Documents
        </h1>
      </div>

      {/* Search */}
      <div style={{ padding: '14px 20px 8px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: theme.raised, border: `1px solid ${theme.rule}`,
          borderRadius: 12, padding: '10px 14px',
        }}>
          <Icon name="search" size={16} color={theme.inkMute}/>
          <input
            value={q} onChange={e => setQ(e.target.value)}
            placeholder="Search agreements, statements…"
            style={{
              flex: 1, border: 0, outline: 0, background: 'transparent',
              fontSize: 14, color: theme.ink, fontFamily: 'inherit',
            }}/>
          <button style={{
            padding: '4px 10px', borderRadius: 8,
            background: theme.canvas2, border: `1px solid ${theme.rule}`,
            fontSize: 11, fontWeight: 600, color: theme.inkDim, letterSpacing: 0.4,
          }}>FILTER</button>
        </div>
      </div>

      {/* Folders */}
      <div style={{ padding: '12px 20px 12px' }}>
        <SectionHeader theme={theme}>Folders</SectionHeader>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          {DL_DATA.documents.map(f => (
            <button key={f.folder} style={{
              padding: '14px 12px',
              background: theme.raised, border: `1px solid ${theme.rule}`,
              borderRadius: 14, textAlign: 'left',
              display: 'flex', flexDirection: 'column', gap: 8, minHeight: 96,
            }}>
              <div style={{
                width: 30, height: 30, borderRadius: 8,
                background: theme.canvas2, border: `1px solid ${theme.rule}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><Icon name="folder" size={16} color={theme.accent.solid}/></div>
              <div style={{ fontSize: 12, fontWeight: 600, color: theme.ink, lineHeight: 1.25 }}>{f.folder}</div>
              <div style={{ fontSize: 11, color: theme.inkMute, marginTop: 'auto' }} className="tnum">{f.count} files</div>
            </button>
          ))}
        </div>
      </div>

      {/* Files */}
      <div style={{ padding: '8px 20px 0' }}>
        <SectionHeader theme={theme} action="Sort">Recent files</SectionHeader>
        <Card theme={theme} pad={0}>
          {files.map((f, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
              borderBottom: i < files.length - 1 ? `1px solid ${theme.rule}` : 'none',
            }}>
              <div style={{
                width: 38, height: 46, borderRadius: 6, flexShrink: 0,
                background: theme.canvas2, border: `1px solid ${theme.rule}`,
                position: 'relative',
                display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 6,
              }}>
                <div style={{
                  position: 'absolute', top: 4, right: 4,
                  width: 8, height: 8, borderTop: `1px solid ${theme.rule}`, borderRight: `1px solid ${theme.rule}`,
                }}/>
                <span className="mono" style={{ fontSize: 8, fontWeight: 700, color: theme.accent.solid, letterSpacing: 0.5 }}>PDF</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500, color: theme.ink, lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 3 }}>
                  <span style={{ fontSize: 11, color: theme.inkMute }}>{f.date}</span>
                  <span style={{ fontSize: 11, color: theme.inkMute }}>·</span>
                  <span className="tnum" style={{ fontSize: 11, color: theme.inkMute }}>{f.size}</span>
                  {f.tag && <span style={{
                    fontSize: 9.5, fontWeight: 700, letterSpacing: 0.6,
                    color: theme.accent.ink, background: theme.accent.soft,
                    padding: '2px 7px', borderRadius: 99, marginLeft: 2,
                  }}>{f.tag.toUpperCase()}</span>}
                </div>
              </div>
              <button onClick={() => downloadClientDoc(f.id, f.name)} title="Download" style={{ color: theme.inkDim, padding: 4 }}>
                <Icon name="download" size={16} color={theme.inkDim}/>
              </button>
            </div>
          ))}
          {files.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute, fontSize: 13 }}>
              No documents yet. Your specialist will upload statements and agreements here as your case progresses.
            </div>
          )}
        </Card>
      </div>

      <div style={{ padding: '24px 20px 0', fontSize: 11.5, color: theme.inkMute, textAlign: 'center', lineHeight: 1.5 }}>
        Need a document we don't have on file? Message your specialist from the Account tab.
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PROFILE / CONCIERGE SCREEN
// ─────────────────────────────────────────────────────────────
function ProfileScreen({ theme, onSignOut, onRefresh }) {
  const d = DL_DATA;
  const sp = d.specialist;
  const [notif, setNotif] = React.useState(true);
  const [paperless, setPaperless] = React.useState(true);

  return (
    <div className="scroll" style={{ height: '100%', overflowY: 'auto', background: theme.canvas, paddingBottom: 110 }}>
      <div style={{ padding: '54px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
          <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 500, letterSpacing: 1.6, textTransform: 'uppercase' }}>Account</div>
          <PwaStatusBadge theme={theme}/>
        </div>
        <h1 className="serif" style={{ fontSize: 32, fontWeight: 400, color: theme.ink, lineHeight: 1, marginTop: 8, letterSpacing: -0.5 }}>
          {d.client.name}
        </h1>
        <div style={{ fontSize: 13, color: theme.inkMute, marginTop: 6 }}>{d.client.biz} · Member since {d.client.memberSince}</div>
      </div>

      {/* Concierge card */}
      {sp ? (
      <div style={{ padding: '14px 20px 16px' }}>
        <div style={{
          background: theme.surface, color: theme.onSurface,
          borderRadius: 22, padding: 20,
          boxShadow: `0 20px 40px -20px ${theme.surface}88`,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ fontSize: 10, color: theme.onSurfaceMute, letterSpacing: 1.8, textTransform: 'uppercase', fontWeight: 500 }}>Your Specialist</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 14 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 99,
              background: `linear-gradient(135deg, ${theme.accent.solid}, ${theme.accent.ink})`,
              color: theme.canvas, fontSize: 18, fontWeight: 600,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'Newsreader, serif',
              border: `2px solid ${theme.surface2}`,
            }}>{sp.initials}</div>
            <div style={{ flex: 1 }}>
              <div className="serif" style={{ fontSize: 20, fontWeight: 500, color: theme.onSurface, lineHeight: 1 }}>{sp.name}</div>
              <div style={{ fontSize: 11.5, color: theme.onSurfaceDim, marginTop: 5 }}>{sp.role || 'Settlement Specialist'}</div>
            </div>
          </div>

          <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {sp.phone && (
              <a href={`tel:${sp.phone}`} style={{
                padding: '11px 12px', borderRadius: 12,
                background: theme.onSurface, color: theme.surface,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                fontSize: 13, fontWeight: 600, textDecoration: 'none',
              }}>
                <Icon name="phone" size={14} color={theme.surface}/>
                Call direct
              </a>
            )}
            {sp.email && (
              <a href={`mailto:${sp.email}`} style={{
                padding: '11px 12px', borderRadius: 12,
                background: 'rgba(245,240,230,0.10)', color: theme.onSurface,
                border: `1px solid rgba(245,240,230,0.18)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                fontSize: 13, fontWeight: 500, textDecoration: 'none',
              }}>
                <Icon name="msg" size={14} color={theme.onSurface}/>
                Message
              </a>
            )}
          </div>

          {sp.phone && (
            <div style={{ marginTop: 12, fontSize: 11, color: theme.onSurfaceMute, lineHeight: 1.5 }}>
              Direct line {sp.phone} · Typically replies within 2 business hours
            </div>
          )}
        </div>
      </div>
      ) : (
        <div style={{ padding: '14px 20px 16px' }}>
          <Card theme={theme} pad={18}>
            <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.4, textTransform: 'uppercase' }}>Your Specialist</div>
            <div style={{ fontSize: 13.5, color: theme.inkDim, marginTop: 8, lineHeight: 1.45 }}>
              A specialist will be assigned to your file shortly. You'll receive a notification when they're ready to introduce themselves.
            </div>
          </Card>
        </div>
      )}

      {/* Account info */}
      <div style={{ padding: '0 20px 16px' }}>
        <SectionHeader theme={theme}>Plan</SectionHeader>
        <Card theme={theme} pad={0}>
          <KV theme={theme} k="Program"        v={d.client.plan}/>
          <KV theme={theme} k="Enrolled debt"  v={`$${DL_DATA.totals.enrolled.toLocaleString()}`}/>
          <KV theme={theme} k="Estimated finish" v="Dec 2027"/>
          <KV theme={theme} k="Client ID"      v={d.client.code} last/>
        </Card>
      </div>

      {/* Settings */}
      <div style={{ padding: '0 20px 16px' }}>
        <SectionHeader theme={theme}>Settings</SectionHeader>
        <Card theme={theme} pad={0}>
          <ToggleRow theme={theme} icon="bell"     title="Push notifications"   sub="Settlement & payment alerts" on={notif} setOn={setNotif}/>
          <ToggleRow theme={theme} icon="doc"      title="Paperless statements" sub="Delivered to your vault"     on={paperless} setOn={setPaperless} last/>
        </Card>
      </div>

      <div style={{ padding: '0 20px 16px' }}>
        <Card theme={theme} pad={0}>
          <NavRow theme={theme} left={<Icon name="shield" size={18} color={theme.inkDim}/>} title="Privacy & security" sub="Encryption, sessions, audit log"/>
          <NavRow theme={theme} left={<Icon name="info" size={18} color={theme.inkDim}/>}   title="Disclosures & legal" sub="Member agreement, FAQ" last/>
        </Card>
      </div>

      <div style={{ padding: '8px 20px 30px' }}>
        <button onClick={onSignOut} style={{
          width: '100%', padding: '13px',
          background: theme.raised, border: `1px solid ${theme.rule}`, borderRadius: 14,
          color: '#B5481D', fontSize: 14, fontWeight: 600,
        }}>Sign out</button>
      </div>
    </div>
  );
}

function KV({ k, v, theme, last }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '13px 16px', borderBottom: last ? 'none' : `1px solid ${theme.rule}`,
    }}>
      <div style={{ fontSize: 13, color: theme.inkMute }}>{k}</div>
      <div style={{ fontSize: 13.5, fontWeight: 500, color: theme.ink }} className="tnum">{v}</div>
    </div>
  );
}

function ToggleRow({ icon, title, sub, on, setOn, theme, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '13px 16px',
      borderBottom: last ? 'none' : `1px solid ${theme.rule}`,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 9, flexShrink: 0,
        background: theme.canvas2, border: `1px solid ${theme.rule}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}><Icon name={icon} size={16} color={theme.ink}/></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: theme.ink }}>{title}</div>
        {sub && <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 2 }}>{sub}</div>}
      </div>
      <button onClick={() => setOn(!on)} style={{
        width: 44, height: 26, borderRadius: 99,
        background: on ? theme.accent.solid : theme.rule,
        position: 'relative', transition: 'background 200ms',
      }}>
        <div style={{
          position: 'absolute', top: 2, left: on ? 20 : 2,
          width: 22, height: 22, borderRadius: 99, background: '#fff',
          boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
          transition: 'left 200ms',
        }}/>
      </button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SETTLEMENT DETAIL SHEET
// ─────────────────────────────────────────────────────────────
function SettlementSheet({ lender, theme, serif, onClose }) {
  if (!lender) return null;
  const stages = ['Contacted', 'Negotiating', 'Offer Received', 'Settled'];
  const stageIdx = stages.indexOf(lender.status);
  const savings = lender.settlement ? lender.balance - lender.settlement : null;

  // Fetch events for this lender from the API
  const eventsRes = useResource(
    () => api.client.activity().then(r => (r.activity || []).filter(e => e.lender_id === lender.id)),
    [lender.id]
  );
  const events = eventsRes.data || [];

  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(10,18,32,0.45)',
        backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
        zIndex: 70,
      }}/>
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        height: '88%', background: theme.canvas,
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        zIndex: 71, overflow: 'hidden',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.3)',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* drag handle + close */}
        <div style={{ paddingTop: 10, display: 'flex', justifyContent: 'center', position: 'relative', flexShrink: 0 }}>
          <div style={{ width: 38, height: 4, borderRadius: 99, background: theme.rule }}/>
          <button onClick={onClose} style={{
            position: 'absolute', right: 16, top: 8,
            width: 30, height: 30, borderRadius: 99,
            background: theme.canvas2, border: `1px solid ${theme.rule}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: theme.ink,
          }}><Icon name="x" size={14} color={theme.ink}/></button>
        </div>

        <div className="scroll" style={{ overflowY: 'auto', flex: 1, padding: '18px 22px 30px' }}>
          {/* Lender masthead */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16,
              background: theme.surface, color: theme.onSurface,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 18, fontWeight: 500, fontFamily: 'Newsreader, serif', letterSpacing: 0.5,
            }}>{lender.short}</div>
            <div style={{ flex: 1 }}>
              <div className="serif" style={{ fontSize: 22, color: theme.ink, fontWeight: 500, lineHeight: 1 }}>{lender.name}</div>
              <div style={{ marginTop: 7 }}><StatusPill status={lender.status} theme={theme}/></div>
            </div>
          </div>

          {/* Three-up metrics */}
          <div style={{
            marginTop: 22,
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
            border: `1px solid ${theme.rule}`, borderRadius: 16, overflow: 'hidden',
            background: theme.raised,
          }}>
            <Stat theme={theme} label="Original" v={lender.balance} serif={serif}/>
            <Stat theme={theme} label="Settlement" v={lender.settlement} serif={serif} border/>
            <Stat theme={theme} label="You save" v={savings} serif={serif} accent border/>
          </div>

          {/* Stepper */}
          <div style={{ marginTop: 24 }}>
            <SectionHeader theme={theme}>Negotiation stage</SectionHeader>
            <div style={{ display: 'flex', alignItems: 'center', padding: '4px 6px 0' }}>
              {stages.map((s, i) => {
                const done = i <= stageIdx;
                const active = i === stageIdx;
                return (
                  <React.Fragment key={s}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                      <div style={{
                        width: 22, height: 22, borderRadius: 99,
                        background: done ? theme.accent.solid : theme.canvas2,
                        border: `1.5px solid ${done ? theme.accent.solid : theme.rule}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        color: '#fff',
                      }}>
                        {done && i < stageIdx ? <Icon name="check" size={11} color="#fff" strokeWidth={2.5}/> : (
                          active ? <div style={{ width: 6, height: 6, borderRadius: 99, background: '#fff' }}/> : null
                        )}
                      </div>
                      <div style={{ fontSize: 10, color: done ? theme.ink : theme.inkMute, fontWeight: 600, marginTop: 6, letterSpacing: 0.3, textAlign: 'center', width: 64, lineHeight: 1.2 }}>
                        {s}
                      </div>
                    </div>
                    {i < stages.length - 1 && (
                      <div style={{
                        flex: 1, height: 2, marginTop: -16,
                        background: i < stageIdx ? theme.accent.solid : theme.rule,
                      }}/>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          </div>

          {/* Negotiation timeline (linked events) */}
          <div style={{ marginTop: 22 }}>
            <SectionHeader theme={theme}>Casefile</SectionHeader>
            <div style={{ position: 'relative', paddingLeft: 16 }}>
              <div style={{
                position: 'absolute', left: 6, top: 6, bottom: 6,
                width: 1.5, background: theme.rule,
              }}/>
              {events.map((e, i) => (
                <div key={e.id || i} style={{ position: 'relative', paddingBottom: 18 }}>
                  <div style={{
                    position: 'absolute', left: -16, top: 4,
                    width: 13, height: 13, borderRadius: 99,
                    background: eventTypeColor(e.type), border: `2.5px solid ${theme.canvas}`,
                  }}/>
                  <div style={{ fontSize: 11, color: theme.inkMute, fontWeight: 500, letterSpacing: 0.2 }}>{e.when} · {e.time}</div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: theme.ink, marginTop: 3 }}>{e.title}</div>
                  {e.body && <div style={{ fontSize: 12.5, color: theme.inkDim, marginTop: 3, lineHeight: 1.4 }}>{e.body}</div>}
                </div>
              ))}
              {!eventsRes.loading && events.length === 0 && (
                <div style={{ fontSize: 12, color: theme.inkMute, padding: '8px 0 4px', fontStyle: 'italic' }}>
                  No events yet for this lender.
                </div>
              )}
            </div>
          </div>

          {/* CTA */}
          {lender.status === 'Offer Received' && (
            <div style={{ marginTop: 12, padding: 16, background: theme.accent.soft, color: theme.accent.ink, borderRadius: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Action requested</div>
              <div style={{ fontSize: 13.5, marginTop: 6, lineHeight: 1.5 }}>
                Approve the {lender.name} settlement offer of <strong>${lender.settlement?.toLocaleString()}</strong>?
                Funds will draft from your reserve account once signed.
              </div>
              <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <button style={{ padding: '11px', borderRadius: 10, background: theme.accent.ink, color: theme.canvas, fontWeight: 600, fontSize: 13 }}>
                  Approve & sign
                </button>
                <button style={{ padding: '11px', borderRadius: 10, background: 'transparent', color: theme.accent.ink, fontWeight: 600, fontSize: 13, border: `1px solid ${theme.accent.ink}` }}>
                  Counter
                </button>
              </div>
            </div>
          )}

          {lender.status === 'Settled' && lender.signed && (
            <div style={{
              marginTop: 12, padding: 14, background: theme.raised,
              border: `1px solid ${theme.rule}`, borderRadius: 14,
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 38, height: 46, borderRadius: 6,
                background: theme.canvas2, border: `1px solid ${theme.rule}`,
                display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 5,
              }}>
                <span className="mono" style={{ fontSize: 8, fontWeight: 700, color: theme.accent.solid }}>PDF</span>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: theme.ink }}>Settlement Agreement</div>
                <div style={{ fontSize: 11.5, color: theme.inkMute, marginTop: 2 }}>Countersigned {lender.signed}</div>
              </div>
              <Icon name="download" size={18} color={theme.ink}/>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function Stat({ label, v, theme, serif, accent, border }) {
  const display = v == null ? '—' : `$${v.toLocaleString()}`;
  return (
    <div style={{ padding: '14px 14px', borderLeft: border ? `1px solid ${theme.rule}` : 'none' }}>
      <div style={{ fontSize: 10, color: theme.inkMute, fontWeight: 600, letterSpacing: 1.2, textTransform: 'uppercase' }}>{label}</div>
      <div className={`tnum ${serif ? 'serif' : ''}`} style={{
        fontSize: 20, marginTop: 5, fontWeight: serif ? 500 : 600, lineHeight: 1,
        color: accent ? theme.accent.solid : theme.ink, letterSpacing: serif ? -0.3 : -0.6,
      }}>
        {display}
      </div>
    </div>
  );
}

function lenderEvents(lender) { return []; } // legacy stub — events now fetched live in SettlementSheet

function eventTypeColor(type) {
  return ({
    settled:     '#2F6A4F',
    offer:       '#1F4A8B',
    payment:     '#193A6E',
    message:     '#9B6B2F',
    negotiation: '#7A2E11',
    document:    '#193A6E',
  })[type] || '#9C9385';
}

// Helper: download a client document via the API + trigger browser save
async function downloadClientDoc(id, filename) {
  try {
    const blob = await api.client.downloadDoc(id);
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename || 'document.pdf';
    document.body.appendChild(a);
    a.click();
    setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 1000);
  } catch (e) {
    console.error('Download failed:', e);
    alert('Could not download this document.');
  }
}

// expose
Object.assign(window, {
  DocsScreen, ProfileScreen, KV, ToggleRow,
  SettlementSheet, Stat, eventTypeColor, downloadClientDoc,
});
