// tab-queries.jsx — F6 Query management & rework workspace
// Log raw query → AI parse → upload missing docs → justification letter → resubmission ZIP

const PCQT_t = window.PCT;
const PCQT_d = window.PCA;

function QueriesTab({ claim, insurer }) {
  const store = useStore();
  const [logOpen, setLogOpen] = React.useState(false);
  const [activeQid, setActiveQid] = React.useState(claim.queries?.[0]?.id || null);

  const queries = claim.queries || [];
  const activeQ = queries.find(q => q.id === activeQid);

  if (queries.length === 0) {
    return (
      <div style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:14 }}>
        <AppCard>
          <AppEmpty
            icon="denial"
            title="No queries on this claim"
            body="If the TPA raises a query, paste their text here and PulseChart will translate it into plain English and tell you which documents are needed."
            action={<AppBtn kind="primary" icon="plus" onClick={() => setLogOpen(true)}>Log a query</AppBtn>}
          />
        </AppCard>
        <SidebarQueryGuide insurer={insurer}/>
        <LogQueryModal open={logOpen} onClose={() => setLogOpen(false)} claim={claim} insurer={insurer}/>
      </div>
    );
  }

  return (
    <div style={{ display:'grid', gridTemplateColumns:'260px 1fr', gap:14 }}>
      {/* Query list rail */}
      <div>
        <AppCard pad={0}>
          <div style={{ padding:'12px 14px', borderBottom:`1px solid ${PCQT_t.c.border}`, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <AppSectionLabel>Queries</AppSectionLabel>
            <button onClick={() => setLogOpen(true)} style={{
              border:'none', background:'transparent', cursor:'pointer',
              padding:'4px 6px', borderRadius:5, color: PCQT_t.c.accent,
              display:'flex', alignItems:'center', gap:4, fontSize:11, fontWeight:600,
            }}>
              <AppIcon name="plus" size={12}/>
              New
            </button>
          </div>
          {queries.map(q => (
            <div key={q.id} onClick={() => setActiveQid(q.id)} style={{
              padding:'12px 14px', cursor:'pointer',
              background: q.id === activeQid ? PCQT_t.c.brandSoft : 'transparent',
              borderBottom: `1px solid ${PCQT_t.c.border}`,
              borderLeft: q.id === activeQid ? `3px solid ${PCQT_t.c.brand}` : '3px solid transparent',
            }}>
              <div style={{ display:'flex', justifyContent:'space-between', gap:8 }}>
                <span style={{ fontFamily: PCQT_t.f.mono, fontSize:10, fontWeight:600, color: PCQT_t.c.textDim, letterSpacing:'.06em', textTransform:'uppercase' }}>
                  {q.source.replace('_','-')}
                </span>
                <span style={{
                  fontSize:9.5, fontWeight:600, fontFamily: PCQT_t.f.mono,
                  padding:'1px 5px', borderRadius:3,
                  background: q.status === 'OPEN' ? PCQT_t.c.warningTint : PCQT_t.c.successTint,
                  color: q.status === 'OPEN' ? PCQT_t.c.warning : PCQT_t.c.success,
                  letterSpacing:'.04em',
                }}>{q.status}</span>
              </div>
              <div style={{ fontSize:12, marginTop:4, color: PCQT_t.c.text, fontWeight: q.id === activeQid ? 600 : 400, lineHeight:1.4 }}>
                {q.plainEnglish ? q.plainEnglish.slice(0,80) + (q.plainEnglish.length > 80 ? '…' : '') : q.rawText.slice(0,80) + '…'}
              </div>
              <div style={{ fontSize:10, color: PCQT_t.c.textDim, fontFamily: PCQT_t.f.mono, marginTop:5 }}>
                {ageAgo(q.raisedAt)}
              </div>
            </div>
          ))}
        </AppCard>
      </div>

      {/* Active query workspace */}
      <div>
        {activeQ ? (
          <QueryWorkspace claim={claim} query={activeQ} insurer={insurer}/>
        ) : (
          <AppCard><AppEmpty icon="denial" title="Pick a query from the list"/></AppCard>
        )}
      </div>

      <LogQueryModal open={logOpen} onClose={() => setLogOpen(false)} claim={claim} insurer={insurer}/>
    </div>
  );
}

function ageAgo(ts) {
  const m = Math.floor((Date.now() - ts) / 60000);
  if (m < 60) return m + 'm ago';
  if (m < 60*24) return Math.floor(m/60) + 'h ago';
  return Math.floor(m / 60 / 24) + 'd ago';
}

// ── Log Query Modal ─────────────────────────────────────
function LogQueryModal({ open, onClose, claim, insurer }) {
  const store = useStore();
  const [raw, setRaw] = React.useState('');
  const [parsed, setParsed] = React.useState(null);
  const [parsing, setParsing] = React.useState(false);

  const handleParse = () => {
    if (!raw.trim()) return;
    setParsing(true);
    // Simulate AI parse latency
    setTimeout(() => {
      setParsed(simulateAIParse(raw, insurer));
      setParsing(false);
    }, 900);
  };

  const handleSave = () => {
    if (!parsed) return;
    store.addQuery(claim.id, {
      source: claim.status === 'PREAUTH_SUBMITTED' ? 'PRE_AUTH' : 'POST_SUBMISSION',
      rawText: raw,
      parsedAt: Date.now(),
      plainEnglish: parsed.plainEnglish,
      requiredDocs: parsed.requiredDocs,
      urgency: parsed.urgency,
      uploaded: [],
      status: 'OPEN',
    });
    setRaw(''); setParsed(null);
    onClose();
  };

  return (
    <AppModal
      open={open} onClose={() => { setRaw(''); setParsed(null); onClose(); }}
      title="Log a TPA query"
      subtitle={`From ${insurer.name} · paste the verbatim text below`}
      width={680}
      footer={
        <>
          <AppBtn kind="ghost" onClick={() => { setRaw(''); setParsed(null); onClose(); }}>Cancel</AppBtn>
          {parsed
            ? <AppBtn kind="primary" icon="check" onClick={handleSave}>Save &amp; open workspace</AppBtn>
            : <AppBtn kind="brand" icon="sparkle" onClick={handleParse} disabled={!raw.trim() || parsing}>
                {parsing ? 'Parsing…' : 'Parse with AI'}
              </AppBtn>}
        </>
      }
    >
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <AppField
          label="Raw query text from TPA"
          required
          hint="Copy-paste verbatim. PulseChart's AI translates the TPA-speak and tells you which documents are needed."
        >
          <AppTextarea
            value={raw} onChange={setRaw}
            placeholder="Pls justify ICU need given vitals stable per admn note. Submit nursing flow chart past 24hr & consultant note explaining medical necessity..."
            rows={5}
          />
        </AppField>

        {parsing && (
          <div style={{
            padding:'14px 16px', background: PCQT_t.c.brandSoft, borderRadius:7,
            display:'flex', alignItems:'center', gap:12, color:'#4C1D95', fontSize:12.5,
          }}>
            <SpinnerSVG/>
            Analysing the query text…
          </div>
        )}

        {parsed && !parsing && (
          <div style={{
            padding:'14px 16px', background: PCQT_t.c.brandSoft, borderRadius:7,
          }}>
            <div style={{
              display:'flex', alignItems:'center', gap:6, marginBottom:10,
              fontFamily: PCQT_t.f.mono, fontSize:10, fontWeight:600,
              letterSpacing:'.1em', textTransform:'uppercase', color: PCQT_t.c.brand,
            }}>
              <AppIcon name="sparkle" size={12} color={PCQT_t.c.brand}/>
              AI · plain English
            </div>
            <div style={{ fontSize:13, color:'#1E1B4B', lineHeight:1.6, fontWeight:500 }}>{parsed.plainEnglish}</div>

            <div style={{
              marginTop:14,
              fontFamily: PCQT_t.f.mono, fontSize:10, fontWeight:600,
              letterSpacing:'.1em', textTransform:'uppercase', color: PCQT_t.c.brand,
              marginBottom:8,
            }}>Required documents</div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {parsed.requiredDocs.map(d => (
                <span key={d} style={{
                  padding:'3px 9px', borderRadius:999,
                  background:'#fff', color:'#4C1D95',
                  fontSize:11, fontWeight:600, fontFamily: PCQT_t.f.sans,
                  border:`1px solid ${PCQT_t.c.brand}30`,
                }}>{PCQT_d.docTypes[d]?.label || d}</span>
              ))}
            </div>

            <div style={{
              marginTop:12, fontSize:11, color:'#4C1D95',
              display:'flex', alignItems:'center', gap:6,
            }}>
              <AppIcon name="clock" size={12}/>
              <span>Urgency: <strong>{parsed.urgency}</strong> · respond within {parsed.urgency === 'IMMEDIATE' ? 'same day' : parsed.urgency === 'STANDARD' ? '24 hours' : '48 hours'}</span>
            </div>
          </div>
        )}
      </div>
    </AppModal>
  );
}

function SpinnerSVG() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" style={{ animation:'pcSpin 1s linear infinite' }}>
      <circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="2" fill="none" strokeDasharray="20" opacity="0.3"/>
      <path d="M14 8a6 6 0 00-6-6" stroke="currentColor" strokeWidth="2" fill="none"/>
    </svg>
  );
}

// Simulated AI parser — pattern-matches keywords in the raw text
function simulateAIParse(raw, insurer) {
  const t = raw.toLowerCase();
  const docs = new Set();
  let plainEnglish = '';
  let urgency = 'STANDARD';

  // ICU justification pattern
  if (t.match(/icu|intensive|justify.*ward|ward.*justify/)) {
    docs.add('JUSTIFICATION_LETTER');
    docs.add('OT_NOTES');
    plainEnglish = `${insurer.name} wants you to justify why this patient is in ICU instead of a general ward, with consultant clinical justification and supporting nursing/OT records.`;
  }
  if (t.match(/ct scan|ct\b|mri|x-?ray|usg|sonogr|echo|ecg/)) {
    docs.add('DIAGNOSTIC_REPORT');
    if (!plainEnglish) plainEnglish = `${insurer.name} is asking for the diagnostic imaging report(s) and films.`;
  }
  if (t.match(/lab|blood|hba1c|cbc|culture|histo|biopsy/)) {
    docs.add('LAB_REPORT');
    if (!plainEnglish) plainEnglish = `${insurer.name} wants supporting lab reports.`;
  }
  if (t.match(/stent|implant|prosthesis|barcode|sticker/)) {
    docs.add('IMPLANT_BARCODE');
    docs.add('IMPLANT_INVOICE');
    if (!plainEnglish) plainEnglish = `${insurer.name} is asking for implant proof — barcode sticker plus tax invoice from the distributor.`;
  }
  if (t.match(/discharge summary|discharge|d\/s/)) {
    docs.add('DISCHARGE_SUMMARY');
    if (!plainEnglish) plainEnglish = `${insurer.name} needs the discharge summary.`;
  }
  if (t.match(/consult|advice note|admn note|admission note|first consult/)) {
    docs.add('CONSULTATION_PAPER');
    if (!plainEnglish) plainEnglish = `${insurer.name} wants the first consultation note / admission advice paper.`;
  }
  if (t.match(/pre-?op|pre op|operative/)) {
    docs.add('OT_NOTES');
  }
  if (t.match(/kyc|pan|aadhaar/)) {
    docs.add('KYC_FORM');
    docs.add('PAN_CARD');
    docs.add('AADHAAR_MASKED');
  }
  if (t.match(/urgent|immediately|today|same day|forthwith/)) urgency = 'IMMEDIATE';
  if (t.match(/within 48|48 hours|two days/)) urgency = 'EXTENDED';

  if (!plainEnglish) {
    plainEnglish = `${insurer.name} has raised a clarification query. Review the raw text and provide the requested documentation.`;
    docs.add('OTHER');
  }

  return {
    plainEnglish,
    requiredDocs: Array.from(docs),
    urgency,
  };
}

// ── Query Workspace ───────────────────────────────────────
function QueryWorkspace({ claim, query, insurer }) {
  const store = useStore();
  const integrated = useIntegrated();
  const [letterOpen, setLetterOpen] = React.useState(false);
  const [hmsAttaching, setHmsAttaching] = React.useState(false);

  const handleUpload = (docType) => (payload) => {
    const next = [...(query.uploaded || []), docType];
    store.updateQuery(claim.id, query.id, { uploaded: next });
    store.addDocument(claim.id, docType);
    store.toast({ icon: 'whatsapp', title: 'Document attached to query response' });
  };

  const allUploaded = (query.requiredDocs || []).every(d => (query.uploaded || []).includes(d));

  const handleMarkResponded = () => {
    store.updateQuery(claim.id, query.id, { status: 'RESPONDED', resolvedAt: Date.now() });
    store.updateClaim(claim.id, { status: claim.preauthSubmittedAt && !claim.approvedAmount ? 'PREAUTH_SUBMITTED' : claim.status });
    store.toast({ icon: 'whatsapp', title: 'Query marked as responded', body: 'Resubmission ZIP downloaded' });
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      {/* Header */}
      <AppCard>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:14 }}>
          <div>
            <AppSectionLabel>Query from {insurer.name}</AppSectionLabel>
            <div style={{ marginTop:8, fontSize:16, fontWeight:600, lineHeight:1.45 }}>
              {query.plainEnglish}
            </div>
            <div style={{ fontSize:11, color: PCQT_t.c.textDim, fontFamily: PCQT_t.f.mono, marginTop:8 }}>
              {query.source} · raised {ageAgo(query.raisedAt)} · urgency {query.urgency || 'STANDARD'}
            </div>
          </div>
          {query.status === 'OPEN' && (
            <AppBtn kind={allUploaded ? 'success' : 'ghost'} icon="check" onClick={handleMarkResponded} disabled={!allUploaded}>
              Mark responded
            </AppBtn>
          )}
        </div>

        {/* Raw text */}
        <div style={{
          marginTop:14, padding:'12px 14px',
          background: PCQT_t.c.surface2, borderRadius:7,
        }}>
          <div style={{
            fontFamily: PCQT_t.f.mono, fontSize:9.5, fontWeight:600,
            letterSpacing:'.1em', textTransform:'uppercase', color: PCQT_t.c.textDim,
            marginBottom:6,
          }}>Verbatim from TPA</div>
          <div style={{ fontSize:12.5, color: PCQT_t.c.text, lineHeight:1.55, fontFamily: PCQT_t.f.sans, fontStyle:'italic' }}>
            "{query.rawText}"
          </div>
        </div>
      </AppCard>

      {/* HMS auto-attach banner (integrated only, when docs are available) */}
      {integrated && (() => {
        const missing = (query.requiredDocs || []).filter(d => !(query.uploaded || []).includes(d));
        const hmsAvailable = missing.filter(d => HMS_AVAILABLE_DOCS.includes(d));
        if (hmsAvailable.length === 0) return null;
        return (
          <div style={{
            padding:'14px 16px',
            background: PCQT_t.c.brandSoft,
            border:`1px solid ${PCQT_t.c.brand}40`,
            borderRadius:9,
            display:'flex', alignItems:'center', gap:12,
          }}>
            <div style={{
              width:36, height:36, borderRadius:8,
              background:'#fff', color: PCQT_t.c.brand,
              display:'grid', placeItems:'center', flexShrink:0,
            }}>
              <AppIcon name="sparkle" size={16}/>
            </div>
            <div style={{ flex:1, fontSize:12.5, color:'#4C1D95', lineHeight:1.55 }}>
              <div style={{ fontSize:13, fontWeight:600, color:'#3B0764' }}>
                {hmsAvailable.length} of {missing.length} required document{missing.length > 1 ? 's' : ''} already in HMS
              </div>
              <div style={{ marginTop:3 }}>
                {hmsAvailable.map(d => HMS_SERVICE_FOR[d]).filter((v,i,a) => a.indexOf(v) === i).join(' · ')} · click to auto-attach without uploading
              </div>
            </div>
            <AppBtn kind="brand" size="sm" icon="check" disabled={hmsAttaching}
              onClick={() => {
                setHmsAttaching(true);
                setTimeout(() => {
                  hmsAvailable.forEach(d => {
                    store.addDocument(claim.id, d);
                    store.updateQuery(claim.id, query.id, { uploaded: [...(query.uploaded || []), d] });
                  });
                  setHmsAttaching(false);
                  store.toast({ icon:'whatsapp', title:`${hmsAvailable.length} document${hmsAvailable.length > 1 ? 's' : ''} pulled from HMS`, body:'Attached to query response · ready to package' });
                }, 700);
              }}>
              {hmsAttaching ? 'Pulling…' : 'Auto-attach all'}
            </AppBtn>
          </div>
        );
      })()}

      {/* Document uploads */}
      <AppCard>
        <AppSectionLabel right={<span style={{ fontSize:11, color: PCQT_t.c.textDim, fontFamily: PCQT_t.f.mono }}>
          {(query.uploaded || []).length} / {(query.requiredDocs || []).length} uploaded
        </span>}>
          Required documents
        </AppSectionLabel>
        <div style={{ marginTop:14, display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
          {(query.requiredDocs || []).map(docType => {
            const isUp = (query.uploaded || []).includes(docType);
            const fromHms = integrated && HMS_AVAILABLE_DOCS.includes(docType);
            if (isUp) {
              return (
                <div key={docType} style={{ position:'relative' }}>
                  <DocChip docType={docType}/>
                  {fromHms && (
                    <span style={{ position:'absolute', top:6, right:6 }}>
                      <HmsBadge variant="chip">HMS</HmsBadge>
                    </span>
                  )}
                </div>
              );
            }
            return (
              <UploadZone
                key={docType}
                docType={docType}
                onUpload={handleUpload(docType)}
                compact
              />
            );
          })}
        </div>

        <div style={{ marginTop:14, display:'flex', gap:8 }}>
          <AppBtn kind="brand" icon="sparkle" onClick={() => setLetterOpen(true)}>
            Generate justification letter
          </AppBtn>
          <AppBtn kind="ghost" icon="download" disabled={!allUploaded}>
            Download resubmission ZIP
          </AppBtn>
          <div style={{ flex:1 }}/>
          <div style={{
            fontSize:11, color: PCQT_t.c.textDim, fontFamily: PCQT_t.f.mono,
            display:'flex', alignItems:'center', gap:4,
          }}>
            <AppIcon name="info" size={12}/>
            Files auto-renamed to {insurer.name}'s convention
          </div>
        </div>
      </AppCard>

      {/* Duplicate query escalation */}
      {claim.queries && claim.queries.filter(q => q.id !== query.id).some(prev =>
        (prev.requiredDocs || []).some(d => (query.requiredDocs || []).includes(d))
      ) && (
        <div style={{
          padding:'12px 16px',
          background: PCQT_t.c.errorTint,
          border: `1px solid ${PCQT_t.c.error}30`,
          borderRadius:9,
          display:'flex', alignItems:'flex-start', gap:12,
        }}>
          <AppIcon name="alert" size={16} color={PCQT_t.c.error}/>
          <div style={{ flex:1, fontSize:12.5, color:'#991B1B', lineHeight:1.55 }}>
            <strong>Duplicate query detected.</strong> {insurer.name} has asked for these documents before — generate the dispute letter citing IRDAI guidelines on redundant queries.
          </div>
          <AppBtn size="sm" kind="danger" icon="send">Dispute letter</AppBtn>
        </div>
      )}

      <JustificationLetterModal
        open={letterOpen} onClose={() => setLetterOpen(false)}
        claim={claim} query={query} insurer={insurer}
      />
    </div>
  );
}

// ── Justification Letter Modal ──────────────────────────
function JustificationLetterModal({ open, onClose, claim, query, insurer }) {
  const integrated = useIntegrated();
  const ehrPrefill = integrated ? ehrClinicalPrefill(claim) : '';
  const [indication, setIndication] = React.useState(PCQT_d.indicationTypes[0]);
  const [clinicalDetails, setClinicalDetails] = React.useState(ehrPrefill);
  const [draft, setDraft] = React.useState('');
  const [generating, setGenerating] = React.useState(false);

  // Reset prefill when modal opens (only first time)
  React.useEffect(() => {
    if (open && integrated && !clinicalDetails) {
      setClinicalDetails(ehrClinicalPrefill(claim));
    }
  }, [open]);

  const handleGenerate = () => {
    setGenerating(true);
    setTimeout(() => {
      setDraft(craftJustificationLetter(claim, query, insurer, indication, clinicalDetails));
      setGenerating(false);
    }, 1100);
  };

  return (
    <AppModal
      open={open} onClose={onClose}
      title="Generate justification letter"
      subtitle="Claude drafts the letter · doctor signs the printed copy"
      width={780}
      footer={
        <>
          <AppBtn kind="ghost" onClick={onClose}>Close</AppBtn>
          {draft && <AppBtn kind="ghost" icon="download">Download for printing</AppBtn>}
          {draft && <AppBtn kind="primary" icon="check">Save to claim</AppBtn>}
        </>
      }
    >
      {!draft && !generating && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <AppField label="Indication type" required>
            <AppSelect value={indication} onChange={setIndication} options={PCQT_d.indicationTypes}/>
          </AppField>
          <AppField label="Key clinical facts" required hint={integrated ? 'Pre-filled from clinical-service EHR note. Edit if needed.' : 'What specifically supports this admission/procedure? Mention vitals, lab values, ICD-10 reasoning.'}>
            <AppTextarea
              value={clinicalDetails} onChange={setClinicalDetails} rows={6}
              placeholder="e.g. Patient SpO2 88% on RA at admission · arterial blood gas showed pH 7.31 · required NIV within 30 min of arrival — general ward not equipped for NIV monitoring."
            />
          </AppField>
          {integrated && (
            <div style={{
              padding:'8px 12px', background: PCQT_t.c.brandSoft, borderRadius:6,
              fontSize:11, color:'#4C1D95', lineHeight:1.55, marginTop:-6,
              display:'flex', gap:6, alignItems:'center',
            }}>
              <HmsBadge variant="chip">EHR</HmsBadge>
              <span>Pre-filled from {claim.doctor}'s clinical note in <strong style={{ fontFamily: PCQT_t.f.mono }}>clinical-service</strong>. Edit as needed.</span>
            </div>
          )}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <AppField label="Treating doctor">
              <AppInput value={claim.doctor}/>
            </AppField>
            <AppField label="Doctor registration number">
              <AppInput value={claim.doctorReg} mono/>
            </AppField>
          </div>
          <div style={{ display:'flex', justifyContent:'flex-end' }}>
            <AppBtn kind="brand" icon="sparkle" onClick={handleGenerate} disabled={!clinicalDetails.trim()}>
              Generate with AI
            </AppBtn>
          </div>
        </div>
      )}

      {generating && (
        <div style={{
          padding:'40px 20px', display:'flex', alignItems:'center',
          justifyContent:'center', gap:12, color: PCQT_t.c.brand,
        }}>
          <SpinnerSVG/>
          <span style={{ fontSize:13 }}>Drafting in IRDAI-compliant clinical language…</span>
        </div>
      )}

      {draft && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div style={{
            padding:'10px 12px', background: PCQT_t.c.brandSoft, borderRadius:7,
            fontSize:11.5, color:'#4C1D95', lineHeight:1.55,
            display:'flex', gap:8, alignItems:'flex-start',
          }}>
            <AppIcon name="sparkle" size={14} color={PCQT_t.c.brand}/>
            <span><strong>Draft generated.</strong> Edit below, print, get doctor's signature, then upload signed copy as a query attachment.</span>
          </div>
          <AppTextarea value={draft} onChange={setDraft} rows={18}/>
        </div>
      )}
    </AppModal>
  );
}

function craftJustificationLetter(claim, query, insurer, indication, clinical) {
  const today = new Date().toLocaleDateString('en-IN', { day:'2-digit', month:'long', year:'numeric' });
  return `${PCQT_d.tenant.name}
${PCQT_d.tenant.addressLine}
ROHINI: ${PCQT_d.tenant.rohini} · Reg: ${PCQT_d.tenant.regNumber}

Date: ${today}

To,
The Medical Officer
${insurer.name}

Subject: Justification for ${indication.toLowerCase()} — Claim ${claim.id} — Patient ${claim.patient.name} (${claim.patient.uhid})
Reference: Your query dated ${PCQT_d.dayOnly(query.raisedAt)}

Dear Sir/Madam,

This is with reference to the above-mentioned cashless claim. We respectfully submit the following clinical justification:

CLINICAL CONTEXT
Patient ${claim.patient.name}, ${claim.patient.age}/${claim.patient.gender}, was admitted on ${PCQT_d.dayOnly(claim.admittedAt)} under the care of ${claim.doctor} (Reg ${claim.doctorReg}). The primary diagnosis is ${claim.icd} — ${claim.icdLabel}.

Symptom onset: ${claim.symptomOnset}.

CLINICAL JUSTIFICATION
${clinical}

Based on the above, the chosen course of treatment was medically necessary and the level of care provided is appropriate, justified, and aligned with IRDAI standard treatment guidelines.

We respectfully request expeditious approval of the pre-authorization in line with the IRDAI Health Insurance Regulations, 2016, § 13(4) on response timelines.

For any further clarification, please feel free to reach us on the hospital insurance desk.

Thank you.

Yours sincerely,



______________________________
${claim.doctor}
Reg. No: ${claim.doctorReg}
${claim.ward.split('·')[0].trim()} Department
${PCQT_d.tenant.name}

[Hospital Seal]`;
}

function SidebarQueryGuide({ insurer }) {
  return (
    <AppCard>
      <AppSectionLabel>About queries</AppSectionLabel>
      <div style={{ fontSize:12, color: PCQT_t.c.textMuted, marginTop:10, lineHeight:1.6 }}>
        <p style={{ margin:'0 0 10px' }}>
          TPA queries are written in cryptic shorthand. PulseChart's AI translates them into a plain action checklist with the documents you need.
        </p>
        <p style={{ margin:0 }}>
          {insurer.name} typically responds in <strong style={{ color: PCQT_t.c.text }}>{insurer.slaPreauthMin} min</strong>. Anything longer is escalatable.
        </p>
      </div>
    </AppCard>
  );
}

Object.assign(window, { QueriesTab });

// HMS-available document types: in integrated mode these can be auto-attached
// from the corresponding HMS microservice without manual upload.
window.HMS_AVAILABLE_DOCS = [
  'CONSULTATION_PAPER',   // clinical-service · SOAP notes
  'DIAGNOSTIC_REPORT',    // radiology-service
  'LAB_REPORT',           // lab-service
  'DISCHARGE_SUMMARY',    // clinical-service
  'HOSPITAL_BILL',        // billing-service
  'PAYMENT_RECEIPT',      // billing-service
  'PHARMACY_BILL',        // pharmacy-service
  'OT_NOTES',             // clinical-service
  'IMPLANT_INVOICE',      // pharmacy-service
];
window.HMS_SERVICE_FOR = {
  CONSULTATION_PAPER: 'clinical-service',
  DIAGNOSTIC_REPORT:  'radiology-service',
  LAB_REPORT:         'lab-service',
  DISCHARGE_SUMMARY:  'clinical-service',
  HOSPITAL_BILL:      'billing-service',
  PAYMENT_RECEIPT:    'billing-service',
  PHARMACY_BILL:      'pharmacy-service',
  OT_NOTES:           'clinical-service',
  IMPLANT_INVOICE:    'pharmacy-service',
};

function ehrClinicalPrefill(claim) {
  // Builds a believable EHR-derived clinical fact paragraph based on the claim's
  // ICD-10 and admission context. In production this would pull the doctor's
  // SOAP note from clinical-service.
  const prefills = {
    'I21.0': `Patient presented with crushing chest pain x 4 hours, diaphoretic. ECG showed ST elevation V2-V5 (anterior STEMI). Troponin-I 14 ng/mL (peak). Echocardiogram revealed anterior wall akinesia with EF 38%. Required ICU monitoring for arrhythmia surveillance and IABP standby. Known HTN x 8 years on amlodipine 5mg.`,
    'I21.9': `Substernal chest pain x 6 hours with diaphoresis. ECG inferior wall changes. Troponin elevated. Required ICU for hemodynamic monitoring and cardiology consult.`,
    'O82':   `G3P2L2 · 38 weeks gestation · previous LSCS · elective repeat caesarean planned. No labour. Vitals stable. Indication: previous classical incision precluding TOLAC. Baby live and well at birth, APGAR 9/9.`,
    'S72.0': `Mechanical fall at home 2 days prior. X-ray showed comminuted intertrochanteric fracture R neck of femur, Garden IV. Patient cannot weight-bear. Indication for hip hemiarthroplasty: age 71, displaced fracture, expected delayed union with internal fixation.`,
    'K35.80':`RLQ abdominal pain x 18 hours. WBC 14,500. CT abdomen showed dilated, inflamed appendix with peri-appendiceal fat stranding. No perforation. Indication for laparoscopic appendectomy: imaging-confirmed acute appendicitis with rising inflammatory markers.`,
    'J18.9': `Fever x 5 days, productive cough, breathlessness x 2 days. Known T2DM. CXR shows right lower lobe consolidation. SpO2 92% on room air. ABG showed pH 7.34. Indication for ICU admission: respiratory distress in an immunocompromised diabetic; requires NIV protocol unavailable on general ward.`,
    'I63.9': `Sudden onset right arm weakness and dysarthria, witnessed onset 3 hours prior. NIHSS 8. CT head ruled out haemorrhage. MR brain showed acute left MCA territory infarct. Required ICU monitoring for thrombolysis protocol.`,
  }[claim.icd] || `Patient admitted under ${claim.doctor} on ${claim.symptomOnset}. Course detailed in clinical-service SOAP note. Procedure / admission medically necessary based on documented clinical findings.`;
  return prefills;
}
