// Results dashboard — bill table + summary + side script panel + send-sim.

const fmt = (n) => '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtShort = (n) => '$' + Math.round(n).toLocaleString('en-US');

const StatusTag = ({ status }) => {
  if (status === 'flag')  return <span className="tag flag"><i className="glyph"></i>Flagged</span>;
  if (status === 'watch') return <span className="tag watch"><i className="glyph"></i>Negotiable</span>;
  return <span className="tag ok"><i className="glyph"></i>Within range</span>;
};

// Range bar — shows market low/mid/high band and where THIS bill sits.
const RangeBar = ({ market, billed }) => {
  const lo = market.low;
  const hi = Math.max(market.high, billed) * 1.05;
  const pct = (v) => Math.max(0, Math.min(100, ((v - lo) / (hi - lo)) * 100));
  const bandLeft = pct(market.low);
  const bandRight = pct(market.high);

  return (
    <div>
      <div className="range-bar">
        <div className="range-track"></div>
        <div
          className="range-band"
          style={{ left: bandLeft + '%', right: (100 - bandRight) + '%' }}
        ></div>
        {market.mid > 0 && (
          <div className="range-tick" style={{ left: pct(market.mid) + '%' }}>
            <span className="lbl">{fmtShort(market.mid)}</span>
          </div>
        )}
        <div className="range-tick bill" style={{ left: pct(billed) + '%' }}>
          <span className="lbl">YOU · {fmtShort(billed)}</span>
        </div>
      </div>
      <div className="range-bar-row">
        <span>{fmtShort(market.low)}</span>
        <span>{fmtShort(market.high)}</span>
      </div>
      <div className="label2">{market.label}</div>
    </div>
  );
};

const BillRow = ({ item, expanded, onToggle }) => {
  const showRange = item.flag && item.flag.market && item.flag.market.high > 0;
  return (
    <React.Fragment>
      <div className={`bill-row ${expanded ? 'expanded' : ''}`} onClick={onToggle}>
        <div className="code">
          <div>{item.code}</div>
        </div>
        <div className="desc">
          <span className="name">{item.desc}</span>
          <span className="codetype">{item.codeType}</span>
        </div>
        <div className="qty">×{item.qty}</div>
        <div className="status"><StatusTag status={item.status} /></div>
        <div className={`amount ${item.status === 'flag' && item.flag?.savings ? 'strike' : ''}`}>
          {fmt(item.amount)}
        </div>
        <div className="toggle">＋</div>
      </div>
      <div className={`bill-detail ${expanded ? 'fade-in' : 'collapsed'}`}>
        <div className="col">
          <h4>{item.flag.title}</h4>
          <p>{item.flag.why}</p>
          {item.flag.action && (
            <div className="detail-action">
              <b>What to say:</b>&nbsp; {item.flag.action}
            </div>
          )}
        </div>
        <div className="col">
          {showRange && (
            <div className="market">
              <div className="lbl">Regional benchmark</div>
              <RangeBar market={item.flag.market} billed={item.amount} />
            </div>
          )}
          {!showRange && (
            <div className="market">
              <div className="lbl">Status</div>
              <p style={{ margin: '4px 0 0', fontSize: 'var(--fz-small)', color: 'var(--ink-2)' }}>
                This line should not appear separately. Expected charge: <b>$0</b>.
              </p>
            </div>
          )}
          {item.flag.savings > 0 && (
            <div style={{
              marginTop: 14, padding: '12px 14px',
              border: '1px solid var(--accent)',
              background: 'var(--accent-soft)',
              borderRadius: 4,
              fontSize: 'var(--fz-small)',
              color: 'var(--ink)'
            }}>
              <b>Likely recoverable:</b>{' '}
              <span className="mono" style={{ marginLeft: 8 }}>{fmt(item.flag.savings)}</span>
            </div>
          )}
        </div>
      </div>
    </React.Fragment>
  );
};

const enrichRef = (ref, bill) => {
  if (!ref) return ref;
  const m = String(ref).match(/^\s*(L\d+)\s*$/i);
  if (!m) return ref;
  const item = bill?.items?.find(i => i.id?.toLowerCase() === m[1].toLowerCase());
  return item ? `${m[1]} — ${item.desc}` : ref;
};

const ScriptPanel = ({ script, onSimulate, bill }) => {
  const [editing, setEditing] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const ref = React.useRef(null);

  const text = [
    script.greeting,
    "",
    ...script.body.flatMap(b => [`[${enrichRef(b.ref, bill)}]`, b.line, ""]),
    script.closing
  ].join("\n");

  const copy = () => {
    if (navigator.clipboard) navigator.clipboard.writeText(text).catch(()=>{});
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };

  return (
    <div className="script">
      <div className="eye">/ Negotiation script · 5 talking points</div>
      <h3>Here's exactly what to say.</h3>
      <div
        className="script-body"
        ref={ref}
        contentEditable={editing}
        suppressContentEditableWarning
      >
        <p>{script.greeting}</p>
        {script.body.map((b, i) => (
          <p key={i}>
            <span className="ref">{enrichRef(b.ref, bill)}</span>
            {b.line}
          </p>
        ))}
        <p>{script.closing}</p>
      </div>
      <div className="script-actions">
        <button className="btn sm" onClick={copy}>{copied ? '✓ Copied' : 'Copy script'}</button>
        <button className="btn sm ghost" onClick={() => setEditing(e => !e)}>
          {editing ? 'Done editing' : 'Edit'}
        </button>
        <button className="btn sm accent disabled" disabled aria-disabled="true" title="Coming soon">
          Send to live chat practice →
          <span className="soon-badge">Coming soon</span>
        </button>
      </div>
    </div>
  );
};

const SendSim = ({ active, onClose, bill, script }) => {
  const [stage, setStage] = React.useState(0);

  React.useEffect(() => {
    if (!active) return;
    setStage(0);
    const seq = [600, 1400, 1100, 1300, 1200];
    const timers = [];
    let acc = 0;
    seq.forEach((d, i) => {
      acc += d;
      timers.push(setTimeout(() => setStage(i + 1), acc));
    });
    return () => timers.forEach(clearTimeout);
  }, [active]);

  if (!active) return null;

  const providerShort = (bill?.provider || 'the provider').split(/[·,—-]/)[0].trim();
  const greeting = script?.greeting ||
    `Hi — account ${bill?.account || ''}${bill?.serviceDate ? `, service date ${bill.serviceDate}` : ''}. I'd like to walk through a few line items I have questions about.`;
  const firstAsk = script?.body?.[0]?.line ||
    "Starting with the largest charge — could you have a coder review it against the documentation?";

  return (
    <div className="send-sim fade-in">
      <div className="eye" style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <span>/ Live chat · {providerShort} billing</span>
        <button onClick={onClose} style={{
          background: 'transparent', border: 0, color: 'var(--ink-3)', cursor: 'default', fontSize: 14
        }}>×</button>
      </div>
      <div className="chat-thread">
        <div className="chat-bubble agent">{providerShort} Billing · Hello, this is Mara. How can I help you today?</div>
        {stage >= 1 && <div className="chat-bubble user">{greeting}</div>}
        {stage >= 2 && stage < 3 && <div className="chat-bubble typing">· · ·</div>}
        {stage >= 3 && <div className="chat-bubble agent">Of course. I have your statement open. Which lines?</div>}
        {stage >= 4 && <div className="chat-bubble user">{firstAsk}</div>}
        {stage >= 5 && <div className="chat-bubble typing">· · ·</div>}
      </div>
    </div>
  );
};

const Results = ({ density, onPage, bill: billProp, script: scriptProp }) => {
  const bill = billProp || window.SAMPLE_BILL;
  const script = scriptProp || window.NEGOTIATION_SCRIPT;
  const [expanded, setExpanded] = React.useState(bill.items[0]?.id || null);
  const [simActive, setSimActive] = React.useState(false);

  // Derived figures
  const flagged = bill.items.filter(i => i.status === 'flag');
  const watched = bill.items.filter(i => i.status === 'watch');
  const flaggedAmount = flagged.reduce((s, i) => s + i.amount, 0);
  const estSavings = bill.items.reduce((s, i) => s + (i.flag?.savings || 0), 0);
  const correctedTotal = bill.totalBilled - estSavings;
  const percentile = 81;

  return (
    <div className="fade-in">
      <header className="result-head">
        <div className="container">
          <div className="breadcrumb">
            / Analysis
            {bill.providerType && <span> · {bill.providerType}</span>}
            {bill.zip && <span> · ZIP {bill.zip}</span>}
            {bill.statementDate && <span> · {bill.statementDate}</span>}
          </div>
          <h1>{bill.provider || 'Your bill'}<br/>
            <span style={{ color: 'var(--ink-3)' }}>{bill.providerType}</span>
          </h1>
          <div className="sub">
            {bill.patient && <span>Name: <b>{bill.patient}</b></span>}
            {bill.account && <span>Account: <b className="mono">{bill.account}</b></span>}
            {bill.serviceDate && <span>Service date: <b>{bill.serviceDate}</b></span>}
            <span>{bill.items.length} line items · {flagged.length} flagged · {watched.length} negotiable</span>
          </div>

          <div className="summary-grid">
            <div className="sgrid-cell">
              <span className="k">Total billed</span>
              <span className="v tnum">{fmtShort(bill.totalBilled)}</span>
              <span className="hint">After insurance: {fmtShort(bill.patientResponsibility)}</span>
            </div>
            <div className="sgrid-cell">
              <span className="k">Flagged amount</span>
              <span className="v warn tnum">{fmtShort(flaggedAmount)}</span>
              <span className="hint">{flagged.length} of {bill.items.length} lines flagged</span>
            </div>
            <div className="sgrid-cell">
              <span className="k">Estimated recoverable</span>
              <span className="v accent tnum">{fmtShort(estSavings)}</span>
              <span className="hint">Corrected total: {fmtShort(correctedTotal)}</span>
            </div>
            <div className="sgrid-cell">
              <span className="k">Rate My Bill{bill.zip ? ` · ZIP ${bill.zip}` : ''}</span>
              <span className="v tnum">{percentile}<span style={{ fontSize: 16, color: 'var(--ink-3)', marginLeft: 4 }}>th pct</span></span>
              <span className="hint">You pay more than {percentile}% of comparable bills in your area.</span>
            </div>
          </div>
        </div>
      </header>

      <section className="container">
        <div className="dash">
          <div>
            <div className="section-head" style={{ marginBottom: 18 }}>
              <h2 style={{ fontSize: 28 }}>Itemized review</h2>
              <span className="meta">Tap a line to expand</span>
            </div>
            <div className="bill">
              <div className="bill-head">
                <div>Code</div>
                <div>Service</div>
                <div className="qty-h">Qty</div>
                <div>Status</div>
                <div style={{ textAlign: 'right' }}>Charged</div>
                <div></div>
              </div>
              {bill.items.map(item => (
                <BillRow
                  key={item.id}
                  item={item}
                  expanded={expanded === item.id}
                  onToggle={() => setExpanded(expanded === item.id ? null : item.id)}
                />
              ))}
            </div>

            <div style={{
              marginTop: 18,
              padding: '18px 22px',
              border: '1px solid var(--line)',
              background: 'var(--bg-elev)',
              borderRadius: 4,
              display: 'grid',
              gridTemplateColumns: '1fr auto',
              gap: 18,
              alignItems: 'center'
            }}>
              <div>
                <div style={{ fontSize: 'var(--fz-small)', color: 'var(--ink-3)' }}>Bottom line</div>
                <div className="serif" style={{ fontSize: 22, marginTop: 2 }}>
                  If all flags resolve, your balance drops from <b className="tnum">{fmtShort(bill.totalBilled)}</b> to{' '}
                  <b className="tnum" style={{ color: 'var(--accent)' }}>{fmtShort(correctedTotal)}</b>.
                </div>
              </div>
              <button className="btn" onClick={() => window.print()}>Export PDF report →</button>
            </div>
          </div>

          <aside className="side">
            <ScriptPanel script={script} bill={bill} onSimulate={() => setSimActive(true)} />
            <SendSim active={simActive} onClose={() => setSimActive(false)} bill={bill} script={script} />

            <a
              className="support-card"
              href="https://donate.stripe.com/7sY5kE7XRdvw7Zl4uU0VO03"
              target="_blank"
              rel="noopener noreferrer"
            >
              <div className="eye">/ This one's on us</div>
              <div className="serif support-headline">
                If this saved you money, drop us a few bucks.
              </div>
              <div className="support-sub">
                No accounts, no email lists. Just gas in the tank to keep it running.
              </div>
              <span className="support-cta">Support this tool ↗</span>
            </a>

            <div style={{
              padding: '18px 20px',
              border: '1px solid var(--line)',
              background: 'var(--bg-elev)',
              borderRadius: 4
            }}>
              <div style={{ fontSize: 'var(--fz-micro)', letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>
                / Bill creep
              </div>
              <div className="serif" style={{ fontSize: 18, lineHeight: 1.3, marginBottom: 12 }}>
                We've seen this provider's average bill rise <b style={{ color: 'var(--warn)' }}>+14%</b> over 12 months.
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 44, marginBottom: 8 }}>
                {[42,45,44,47,49,51,52,55,57,58,60,62].map((h, i) => (
                  <div key={i} style={{
                    flex: 1,
                    height: h + '%',
                    background: i === 11 ? 'var(--warn)' : 'var(--ink-4)',
                    borderRadius: 1,
                    opacity: 0.6 + i * 0.03
                  }}></div>
                ))}
              </div>
              <div style={{ fontSize: 'var(--fz-micro)', color: 'var(--ink-3)', display: 'flex', justifyContent: 'space-between' }}>
                <span>Apr '25</span><span>Mar '26</span>
              </div>
              <a onClick={() => onPage('monitor')} style={{
                display: 'inline-block', marginTop: 12,
                fontSize: 'var(--fz-small)', color: 'var(--ink)',
                borderBottom: '1px solid var(--ink)', paddingBottom: 1
              }}>
                Set a creep alert →
              </a>
            </div>
          </aside>
        </div>
      </section>

      <Footer onPage={onPage} />
    </div>
  );
};

Object.assign(window, { Results });
