// Audit Trail tab — Federal return structure with OCR provenance
// Reads top-to-bottom like a 1040: Income → Adjustments → Deductions → Schedule C → Credits.
// Each "line" expands to show the source documents and the exact OCR-extracted fields,
// with arrows showing where each field lands on the return.

const { useState: useStateAudit, useMemo } = React;

const DocPageIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
    <polyline points="14 2 14 8 20 8" />
    <line x1="9" y1="13" x2="15" y2="13" />
    <line x1="9" y1="17" x2="15" y2="17" />
  </svg>
);

const ArrowRightIcon = () => (
  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
    <line x1="5" y1="12" x2="19" y2="12" />
    <polyline points="12 5 19 12 12 19" />
  </svg>
);

const FlagIcon = () => (
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
    <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" />
    <line x1="4" y1="22" x2="4" y2="15" />
  </svg>
);

function AuditTrailTab({ onOpenDoc, activeDocId, activeBoxId }) {
  const { C, ocrAuditTrail } = window.AW_DATA;
  const [confFilter, setConfFilter] = useStateAudit("all");
  const [expandedLines, setExpandedLines] = useStateAudit({});

  const toggleLine = (key) => setExpandedLines(p => ({ ...p, [key]: !p[key] }));

  // Stats
  const stats = useMemo(() => {
    let totalFields = 0, lowConf = 0, flagged = 0;
    ocrAuditTrail.forEach(sec => sec.items.forEach(line => {
      if (line.flag) flagged++;
      line.sources.forEach(src => src.fields.forEach(f => {
        totalFields++;
        if (f.conf === "low") lowConf++;
      }));
    }));
    return { totalFields, lowConf, flagged };
  }, [ocrAuditTrail]);

  return (
    <div style={{ padding: "20px 0 32px" }}>
      {/* Top toolbar — explainer + stats + filter */}
      <div style={{
        background: C.white, border: `1px solid ${C.border}`, borderRadius: 12,
        padding: "16px 20px", marginBottom: 20,
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, flexWrap: "wrap",
      }}>
        <div style={{ flex: "1 1 280px", minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: C.brownDark, marginBottom: 2 }}>
            OCR audit trail · Federal Form 1040, TY 2025
          </div>
          <div style={{ fontSize: 12, color: C.brownMuted, lineHeight: 1.5 }}>
            Every field extracted from source documents, mapped to its destination on the return. Reads top-to-bottom in 1040 order.
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: C.brownDark }}>{stats.totalFields}</div>
            <div style={{ fontSize: 10, color: C.brownMuted, textTransform: "uppercase", letterSpacing: "0.06em" }}>Fields</div>
          </div>
          <div style={{ width: 1, height: 28, background: C.border }} />
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: stats.lowConf > 0 ? C.low : C.brownDark }}>{stats.lowConf}</div>
            <div style={{ fontSize: 10, color: C.brownMuted, textTransform: "uppercase", letterSpacing: "0.06em" }}>Low conf.</div>
          </div>
          <div style={{ width: 1, height: 28, background: C.border }} />
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: stats.flagged > 0 ? C.amber : C.brownDark }}>{stats.flagged}</div>
            <div style={{ fontSize: 10, color: C.brownMuted, textTransform: "uppercase", letterSpacing: "0.06em" }}>Flagged</div>
          </div>
        </div>
      </div>

      {/* Filter pills */}
      <div style={{ display: "flex", gap: 6, marginBottom: 20, alignItems: "center" }}>
        <span style={{ fontSize: 11, color: C.brownMuted, marginRight: 6 }}>View:</span>
        {[
          { key: "all", label: "Everything" },
          { key: "low", label: "Low confidence only" },
          { key: "flagged", label: "Flagged only" },
        ].map(f => (
          <button key={f.key} onClick={() => setConfFilter(f.key)} style={{
            padding: "5px 14px", borderRadius: 20, fontSize: 12, fontWeight: 500,
            border: `1px solid ${confFilter === f.key ? C.brownDark : C.border}`,
            background: confFilter === f.key ? C.brownDark : C.white,
            color: confFilter === f.key ? "#fff" : C.brownText,
            cursor: "pointer", fontFamily: "inherit",
          }}>{f.label}</button>
        ))}
      </div>

      {/* Sections */}
      <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
        {ocrAuditTrail.map((section, sIdx) => {
          // Filter pass-through check
          const visibleItems = section.items.filter(line => {
            if (confFilter === "flagged") return !!line.flag;
            if (confFilter === "low") {
              return line.sources.some(s => s.fields.some(f => f.conf === "low"));
            }
            return true;
          });
          if (visibleItems.length === 0) return null;

          return (
            <SectionBlock
              key={sIdx}
              section={section}
              visibleItems={visibleItems}
              sIdx={sIdx}
              expandedLines={expandedLines}
              toggleLine={toggleLine}
              confFilter={confFilter}
              onOpenDoc={onOpenDoc}
              activeDocId={activeDocId}
              activeBoxId={activeBoxId}
            />
          );
        })}
      </div>
    </div>
  );
}

function SectionBlock({ section, visibleItems, sIdx, expandedLines, toggleLine, confFilter, onOpenDoc, activeDocId, activeBoxId }) {
  const { C } = window.AW_DATA;
  return (
    <div>
      {/* Big section header — "Income", "Itemized deductions", etc. */}
      <div style={{
        display: "flex", alignItems: "baseline", justifyContent: "space-between",
        marginBottom: 14, paddingBottom: 10,
        borderBottom: `2px solid ${C.brownDark}`,
      }}>
        <div>
          <h3 style={{
            margin: 0, fontSize: 18, fontWeight: 700, color: C.brownDark,
            letterSpacing: "-0.01em",
          }}>{section.section}</h3>
          <div style={{ fontSize: 11, color: C.brownMuted, marginTop: 3, fontFamily: "ui-monospace, 'SF Mono', monospace" }}>
            {section.line}
          </div>
        </div>
      </div>

      {/* Line items */}
      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {visibleItems.map((line, lIdx) => {
          const key = `${sIdx}-${lIdx}`;
          return (
            <LineItem
              key={key}
              line={line}
              lineKey={key}
              open={!!expandedLines[key]}
              toggle={() => toggleLine(key)}
              confFilter={confFilter}
              onOpenDoc={onOpenDoc}
              activeDocId={activeDocId}
              activeBoxId={activeBoxId}
            />
          );
        })}
      </div>
    </div>
  );
}

function LineItem({ line, lineKey, open, toggle, confFilter, onOpenDoc, activeDocId, activeBoxId }) {
  const { C } = window.AW_DATA;

  // Worst-case confidence across line
  const worstConf = (() => {
    const all = line.sources.flatMap(s => s.fields.map(f => f.conf));
    if (all.includes("low")) return "low";
    if (all.includes("medium")) return "medium";
    return "high";
  })();

  return (
    <div style={{ borderBottom: `1px solid ${C.border}` }}>
      <div onClick={toggle} style={{
        display: "flex", alignItems: "center", padding: "16px 4px",
        cursor: "pointer", gap: 14,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: C.brownDark }}>{line.category}</span>
            {line.flag && (
              <span style={{
                display: "inline-flex", alignItems: "center", gap: 4,
                fontSize: 10, fontWeight: 600, padding: "2px 8px", borderRadius: 10,
                background: "#FFF3D6", color: C.amber, textTransform: "uppercase", letterSpacing: "0.04em",
              }}>
                <FlagIcon /> {line.flag}
              </span>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: C.brownMuted, fontFamily: "ui-monospace, 'SF Mono', monospace" }}>
            → {line.returnLine}
          </div>
        </div>
        <span style={{ fontSize: 16, fontWeight: 700, color: C.brownDark, whiteSpace: "nowrap" }}>{line.total}</span>
        <ConfBadge level={worstConf} />
        <ChevronDown open={open} />
      </div>

      {open && (
        <div style={{ padding: "4px 0 22px 4px" }}>
          {line.sources.map((src, idx) => (
            <SourceCard
              key={idx}
              src={src}
              confFilter={confFilter}
              onOpenDoc={onOpenDoc}
              activeDocId={activeDocId}
              activeBoxId={activeBoxId}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function SourceCard({ src, confFilter, onOpenDoc, activeDocId, activeBoxId }) {
  const isActive = !!src.docId && activeDocId === src.docId;
  const { C } = window.AW_DATA;
  const visibleFields = src.fields.filter(f => confFilter === "low" ? f.conf === "low" : true);
  if (visibleFields.length === 0 && confFilter === "low") return null;

  return (
    <div style={{
      background: C.white,
      border: `1px solid ${isActive ? C.greenAccent : C.border}`,
      boxShadow: isActive ? `0 0 0 2px ${C.greenAccent}22` : "none",
      borderRadius: 10,
      marginBottom: 10, overflow: "hidden",
      transition: "all 0.15s",
    }}>
      {/* Source header — which document this came from */}
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "10px 14px", background: C.cream,
        borderBottom: `1px solid ${C.border}`,
      }}>
        <span style={{ color: C.brownText, display: "flex" }}><DocPageIcon /></span>
        <span style={{ fontSize: 12.5, fontWeight: 600, color: C.brownDark }}>{src.doc}</span>
        <span style={{ fontSize: 11, color: C.brownMuted }}>· {src.page}</span>
        <div style={{ flex: 1 }} />
        {src.docId && (
          <SourceLink
            label={isActive ? "Showing in viewer" : "Open in viewer →"}
            onClick={() => onOpenDoc && onOpenDoc(src.docId)}
          />
        )}
      </div>

      {/* Fields table — extracted value → return destination */}
      <div>
        {/* Column header */}
        <div style={{
          display: "grid", gridTemplateColumns: "1.4fr 1fr auto 1.4fr auto",
          gap: 14, padding: "8px 14px",
          fontSize: 10, color: C.brownMuted, textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600,
          background: C.cream, borderBottom: `1px solid ${C.border}`,
        }}>
          <span>OCR field</span>
          <span style={{ textAlign: "right" }}>Extracted value</span>
          <span style={{ width: 12 }} />
          <span>Return destination</span>
          <span style={{ width: 50, textAlign: "right" }}>Conf.</span>
        </div>

        {visibleFields.map((field, idx) => {
          const fieldActive = isActive && activeBoxId === field.boxId;
          return (
          <div
            key={idx}
            onClick={() => field.boxId && src.docId && onOpenDoc && onOpenDoc(src.docId, field.boxId)}
            style={{
              display: "grid", gridTemplateColumns: "1.4fr 1fr auto 1.4fr auto",
              gap: 14, padding: "10px 14px",
              alignItems: "start",
              borderBottom: idx < visibleFields.length - 1 ? `1px solid ${C.border}` : "none",
              background: fieldActive ? "#EBF2E2" : field.conf === "low" ? "#FFF9F0" : "transparent",
              cursor: field.boxId && src.docId ? "pointer" : "default",
              transition: "background 0.12s",
            }}>
            <div style={{ fontSize: 12.5, color: C.brownText, lineHeight: 1.4 }}>{field.box}</div>
            <div style={{
              fontSize: 13, color: C.brownDark, fontWeight: 600, textAlign: "right",
              fontFamily: "ui-monospace, 'SF Mono', monospace",
            }}>{field.value}</div>
            <div style={{ color: C.brownMuted, marginTop: 3 }}><ArrowRightIcon /></div>
            <div style={{
              fontSize: 11.5, color: C.greenDark, fontWeight: 500, lineHeight: 1.4,
              fontFamily: "ui-monospace, 'SF Mono', monospace",
            }}>{field.line}</div>
            <div style={{ textAlign: "right" }}>
              <ConfBadge level={field.conf} size="xs" />
            </div>
            {field.note && (
              <div style={{
                gridColumn: "1 / -1", marginTop: 6, padding: "8px 12px",
                background: field.conf === "low" ? "#FDE8E8" : "#FFF3D6",
                borderRadius: 6, fontSize: 11.5, color: field.conf === "low" ? C.low : C.amber, lineHeight: 1.5,
              }}>
                <span style={{ fontWeight: 600 }}>Note · </span>{field.note}
              </div>
            )}
          </div>
          );
        })}
      </div>
    </div>
  );
}

window.AuditTrailTab = AuditTrailTab;
