// app-upload.jsx — document upload zone + demo document chooser.
// Supports drag-drop (any file → uses filename to "OCR") AND
// click-to-load (picks from pre-canned demo doc set).

const PCAU_t = window.PCT;
const PCAU_d = window.PCA;

// ── Upload Zone ───────────────────────────────────────────
// Renders an empty slot for a doc type. On drop OR click,
// either accepts a real file (we read name only) or opens the
// demo-doc chooser modal.
function UploadZone({ docType, label, required, onUpload, compact }) {
  const [drag, setDrag] = React.useState(false);
  const [picker, setPicker] = React.useState(false);
  const docMeta = PCAU_d.docTypes[docType] || { label: docType };

  const handleDrop = (e) => {
    e.preventDefault();
    setDrag(false);
    const file = e.dataTransfer.files[0];
    if (file) {
      // We don't store the file — we just acknowledge it.
      onUpload({
        source: 'drop',
        fileName: file.name,
        docType,
        ocrPreview: simulateOCR(docType, file.name),
      });
    }
  };

  return (
    <>
      <div
        onDragOver={e => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={handleDrop}
        onClick={() => setPicker(true)}
        style={{
          border: drag ? `2px dashed ${PCAU_t.c.accent}` : `1.5px dashed ${PCAU_t.c.borderStrong}`,
          background: drag ? PCAU_t.c.accentTint : PCAU_t.c.surface2,
          borderRadius: 9,
          padding: compact ? '12px 14px' : '18px 16px',
          cursor:'pointer',
          transition:'background .12s, border-color .12s',
          display:'flex', alignItems:'center', gap: compact ? 10 : 12,
        }}
      >
        <div style={{
          width: compact ? 32 : 40, height: compact ? 32 : 40, borderRadius: 8,
          background: '#fff',
          border: `1px solid ${PCAU_t.c.border}`,
          display:'grid', placeItems:'center', flexShrink: 0,
          color: PCAU_t.c.textMuted,
        }}>
          <AppIcon name="upload" size={compact ? 14 : 16}/>
        </div>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:6 }}>
            <span style={{ fontSize:13, fontWeight:500, color: PCAU_t.c.text }}>{label || docMeta.label}</span>
            {required && <span style={{ fontSize:10, color: PCAU_t.c.error, fontWeight:600 }}>·  required</span>}
          </div>
          <div style={{ fontSize:11, color: PCAU_t.c.textMuted, marginTop:2 }}>
            Drag a file here, or click to pick a demo document
          </div>
        </div>
      </div>

      <DocumentPickerModal
        open={picker}
        onClose={() => setPicker(false)}
        docType={docType}
        onPick={(doc) => {
          setPicker(false);
          onUpload({
            source: 'demo',
            fileName: doc.label,
            docType,
            demoDoc: doc,
            ocrPreview: simulateOCR(docType, doc.label, doc),
          });
        }}
      />
    </>
  );
}

// ── DocumentPickerModal ───────────────────────────────────
function DocumentPickerModal({ open, onClose, docType, onPick }) {
  const available = PCAU_d.demoDocuments[docType] || [];
  const docMeta = PCAU_d.docTypes[docType] || { label: docType };

  return (
    <AppModal
      open={open} onClose={onClose}
      title={`Pick a demo document`}
      subtitle={`Document type: ${docMeta.label}`}
      width={620}
    >
      {available.length === 0 ? (
        <AppEmpty
          icon="docs"
          title="No demo documents for this type"
          body="Use drag-drop with any file from your machine — the demo will treat its name as the document and proceed."
        />
      ) : (
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {available.map(d => (
            <div key={d.id}
              onClick={() => onPick(d)}
              style={{
                padding:'14px 16px',
                background: PCAU_t.c.surface2,
                border: `1px solid ${PCAU_t.c.border}`,
                borderRadius:8,
                display:'flex', alignItems:'center', gap:14,
                cursor:'pointer',
                transition:'background .12s',
              }}
              onMouseEnter={e => e.currentTarget.style.background = '#FAFAF9'}
              onMouseLeave={e => e.currentTarget.style.background = PCAU_t.c.surface2}
            >
              <DocThumb doc={d} docType={docType} size="md"/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13.5, fontWeight:500 }}>{d.label}</div>
                <DocMetaLine doc={d} docType={docType}/>
              </div>
              <AppBtn size="sm" kind="ghost" icon="check">Use this</AppBtn>
            </div>
          ))}
        </div>
      )}
      <div style={{
        marginTop:16, padding:'12px 14px',
        background: PCAU_t.c.accentTint, borderRadius:7,
        fontSize:11.5, color:'#075985', lineHeight:1.55,
        display:'flex', gap:8, alignItems:'flex-start',
      }}>
        <AppIcon name="info" size={14} color={PCAU_t.c.accent}/>
        <span>
          <strong>Demo mode.</strong> Picking a document instantly "uploads" it and runs the OCR mock. In production this is real file storage + Google Cloud Vision OCR.
        </span>
      </div>
    </AppModal>
  );
}

// ── DocThumb — visual preview of a demo doc ──────────────
function DocThumb({ doc, docType, size = 'md' }) {
  const dim = size === 'sm' ? 36 : size === 'lg' ? 84 : 52;
  const meta = PCAU_d.docTypes[docType] || {};
  const kind = doc.kind || meta.icon || 'doc';

  // Distinct visual treatment per doc type
  if (docType === 'ID_PROOF' && kind === 'aadhaar') {
    return (
      <div style={{ width: dim, height: dim * 0.62, borderRadius:5, background:'#FEF7E0', border:'1px solid #F59E0B30', padding:4, fontSize: dim/12, lineHeight:1.1, color:'#92400E', fontWeight:600, fontFamily: PCAU_t.f.mono }}>
        AADHAAR<br/>
        <span style={{ fontWeight:400, opacity:.7 }}>{doc.maskedId || '•••• •••• ••••'}</span>
      </div>
    );
  }
  if (docType === 'ID_PROOF' && kind === 'pan') {
    return (
      <div style={{ width: dim, height: dim * 0.62, borderRadius:5, background:'#E0F2FE', border:'1px solid #0EA5E930', padding:4, fontSize: dim/12, color:'#075985', fontWeight:600, fontFamily: PCAU_t.f.mono, lineHeight:1.1 }}>
        PAN<br/>
        <span style={{ fontWeight:400 }}>{doc.maskedId || 'XXXXX0000X'}</span>
      </div>
    );
  }
  if (docType === 'INSURANCE_CARD' || docType === 'CANCELLED_CHEQUE') {
    return (
      <div style={{
        width: dim, height: dim * 0.62, borderRadius:5,
        background: docType === 'CANCELLED_CHEQUE' ? '#FCE7F3' : 'linear-gradient(135deg, #1E40AF, #1E3A8A)',
        padding:4, color: docType === 'CANCELLED_CHEQUE' ? '#9D174D' : '#fff',
        fontSize: dim/12, fontFamily: PCAU_t.f.mono, fontWeight:600, lineHeight:1.1,
      }}>
        {docType === 'CANCELLED_CHEQUE' ? 'CHEQUE' : (doc.insurer || 'INS').toUpperCase().slice(0,10)}
      </div>
    );
  }
  // Default: paper preview
  return (
    <div style={{
      width: dim, height: dim * 1.2, borderRadius:4,
      background:'#fff', border:`1px solid ${PCAU_t.c.border}`,
      padding:5, fontFamily: PCAU_t.f.sans,
    }}>
      <div style={{ height:3, background: PCAU_t.c.text, borderRadius:1, width:'70%', marginBottom:3 }}/>
      <div style={{ height:2, background: PCAU_t.c.border, borderRadius:1, width:'50%', marginBottom:4 }}/>
      {[60,80,55,75,40].map((w, i) => (
        <div key={i} style={{ height:1.5, background: PCAU_t.c.border, borderRadius:1, width: `${w}%`, marginBottom:2 }}/>
      ))}
    </div>
  );
}

function DocMetaLine({ doc, docType }) {
  const bits = [];
  if (doc.maskedId) bits.push(doc.maskedId);
  if (doc.policyNumber) bits.push(doc.policyNumber);
  if (doc.insurer && docType !== 'INSURANCE_CARD') bits.push(doc.insurer);
  if (doc.amount != null) bits.push(PCAU_d.inr(doc.amount));
  if (doc.total != null) bits.push(PCAU_d.inr(doc.total));
  if (doc.findings) bits.push(doc.findings);
  if (doc.body && bits.length === 0) bits.push(doc.body.slice(0, 80));
  if (doc.brand && doc.batch) bits.push(`${doc.brand} · ${doc.batch}`);
  if (doc.doctor) bits.push(doc.doctor);
  if (bits.length === 0) return null;
  return (
    <div style={{ fontSize:11, color: PCAU_t.c.textMuted, marginTop:3, fontFamily: PCAU_t.f.mono, letterSpacing:'.01em', display:'flex', flexWrap:'wrap', gap:8 }}>
      {bits.map((b, i) => <span key={i}>{i > 0 && <span style={{ color: PCAU_t.c.textDim, marginRight:8 }}>·</span>}{b}</span>)}
    </div>
  );
}

// ── Simulated OCR — generates believable extracted fields ─
function simulateOCR(docType, fileName, demoDoc) {
  if (demoDoc) {
    // Use the demo doc's data directly
    return {
      success: true,
      fields: { ...demoDoc },
      detectedType: docType,
    };
  }
  // Real file dropped — generate something believable from the filename
  const guesses = {
    ID_PROOF: { name: 'Patient name extracted', dob: '1962-03-14', idMasked: '•••• •••• 4421' },
    INSURANCE_CARD: { policyNumber: 'P/181000/01/2025/A032177', insurer: 'Star Health', sumInsured: 1000000 },
    CONSULTATION_PAPER: { doctor: 'Dr. Anand Krishnan', date: '24 May 2026' },
    DISCHARGE_SUMMARY: { admissionDate: '24 May 2026', dischargeDate: '27 May 2026', icd: 'I21.0' },
  };
  return {
    success: true,
    fields: guesses[docType] || { extracted: 'OK' },
    detectedType: docType,
  };
}

// ── DocChip — shows an already-uploaded doc on a claim ───
function DocChip({ docType, onRemove, demoDocId, compact }) {
  const meta = PCAU_d.docTypes[docType] || { label: docType };
  // Try to find the demo doc for richer preview
  const available = PCAU_d.demoDocuments[docType] || [];
  const doc = demoDocId ? available.find(d => d.id === demoDocId) : available[0];

  return (
    <div style={{
      display:'flex', alignItems:'center', gap:10,
      padding: compact ? '8px 10px' : '10px 12px',
      background: PCAU_t.c.surface2,
      borderRadius: 7,
      border: `1px solid ${PCAU_t.c.border}`,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius:6,
        background: '#fff', border: `1px solid ${PCAU_t.c.border}`,
        display:'grid', placeItems:'center', flexShrink:0,
        color: PCAU_t.c.textMuted,
      }}>
        <AppIcon name="docs" size={13}/>
      </div>
      <div style={{ minWidth:0, flex:1 }}>
        <div style={{ fontSize:12.5, color: PCAU_t.c.text, fontWeight:500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{meta.label}</div>
        {doc && <div style={{ fontSize:10.5, color: PCAU_t.c.textMuted, fontFamily: PCAU_t.f.mono, marginTop:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{doc.label}</div>}
      </div>
      <div style={{
        display:'flex', alignItems:'center', gap:4,
        padding:'2px 6px', borderRadius:4,
        background: PCAU_t.c.successTint, color: PCAU_t.c.success,
        fontSize:10, fontWeight:600, fontFamily: PCAU_t.f.mono, letterSpacing:'.02em',
      }}>
        <AppIcon name="check" size={10}/>
        OCR
      </div>
      {onRemove && (
        <button onClick={onRemove} style={{
          border:'none', background:'transparent', cursor:'pointer',
          width:22, height:22, borderRadius:5,
          display:'grid', placeItems:'center', color: PCAU_t.c.textMuted,
        }}>
          <AppIcon name="x" size={12}/>
        </button>
      )}
    </div>
  );
}

Object.assign(window, { UploadZone, DocumentPickerModal, DocThumb, DocChip, simulateOCR });
