(function() {
const h = React.createElement;
const { useMemo } = React;

// Plain-English "why this matters" derived from the real monthly series.
function generateWhyItMatters(name, category, monthly, avg) {
  const cat = (category || '').toLowerCase();
  const n = (name || '').toLowerCase();
  const isRising = monthly.length >= 2 && monthly[monthly.length-1].amount > monthly[monthly.length-2].amount;
  const aboveAvgMonths = monthly.filter(m => m.amount > avg * 1.1).length;
  if (cat.includes('salary') || cat.includes('payroll') || n.includes('salary') || n.includes('wage')) {
    return `Staff costs are typically the largest expense in a business. ${isRising ? 'This account is trending upward — review headcount and overtime.' : 'Costs are stable — monitor for planned increases.'} ${aboveAvgMonths > 2 ? `${aboveAvgMonths} months exceeded the average.` : ''}`;
  }
  if (cat.includes('revenue') || cat.includes('income')) {
    return `Revenue is the lifeblood of the business. ${isRising ? 'This income stream is growing — a positive signal.' : 'Revenue has softened recently — investigate the cause and address promptly.'}`;
  }
  if (cat.includes('rent') || n.includes('rent')) {
    return `Occupancy costs are typically fixed. ${aboveAvgMonths > 0 ? 'Recent months show elevated spend — check for additional charges or rate increases.' : 'Spend is consistent with expectations.'}`;
  }
  return `This account ${isRising ? 'is trending upward' : 'has been broadly stable'} over the review period. ${aboveAvgMonths > 2 ? `${aboveAvgMonths} of ${monthly.length} months exceeded the average — worth investigating.` : 'Spend patterns appear normal.'}`;
}

// Generic, non-fabricated improvement suggestions keyed off the account type.
function generateHowToImprove(name, category) {
  const cat = (category || '').toLowerCase();
  const n = (name || '').toLowerCase();
  if (cat.includes('salary') || cat.includes('payroll') || n.includes('salary') || n.includes('wage')) {
    return ['Review overtime and contractor spend for reductions', 'Benchmark salaries against industry rates annually', 'Consider performance-linked bonuses vs fixed increases'];
  }
  if (cat.includes('revenue') || cat.includes('income')) {
    return ['Identify top revenue sources and protect them', 'Review pricing — consider annual CPI-linked increases', 'Analyse customer concentration risk'];
  }
  if (n.includes('rent') || cat.includes('rent')) {
    return ['Review lease terms and renegotiate at renewal', 'Consider subleasing unused space', 'Compare market rates in your area'];
  }
  return ['Review invoices for accuracy and duplicates', 'Compare rates with alternative suppliers', 'Set a monthly budget and track variance'];
}

function AccountDetailPanel({ account, txns, plHistory, onClose, onViewTransactions }) {
  // account = { name, category, page } — what was clicked
  // txns = data.txns — full transaction list
  // V2 drill enhancements (analysis block) are opt-in via the same flag as the
  // V2 shell — existing users see the original panel unchanged.
  const v2 = (() => { try { return window.localStorage.getItem('perdura_v2shell') === '1'; } catch (e) { return false; } })();

  // Global period (mirror of globalPeriod.resolved, set in app.jsx). Read fresh
  // each render — the panel mounts after the user has picked a period, so it
  // always reflects the current selection. "YYYY-MM" keys.
  const periodMonths = window.__periodMonths || [];
  const periodLabel  = window.__globalPeriod || 'LTM';
  const hasPeriod    = periodMonths.length > 0;

  // Filter transactions for this account — within the selected period.
  const acctTxns = useMemo(() => {
    if (!txns || !account) return [];
    const name    = (account.name||'').toLowerCase().trim();
    const acctCat = (account.category||'').toLowerCase().trim();
    return txns.filter(t => {
      const a = (t.account_name||'').toLowerCase().trim();
      const c = (t.canonical_category||'').toLowerCase().trim();
      const m = (t.posted_date||t.date||'').slice(0,7);

      // Period filter first — cheap reject.
      const inPeriod = !hasPeriod || periodMonths.includes(m);
      if (!inPeriod) return false;

      // Match: exact name first, then prefix / word-boundary — never a bare
      // substring, which used to bleed "Rent" into "Rent Deposit".
      if (name) {
        return a === name ||
               a.startsWith(name) ||
               name.startsWith(a) ||
               a.includes(' ' + name) ||
               name.includes(' ' + a);
      }
      // Category-only drill (e.g. a mix row with no specific account).
      if (acctCat) return c === acctCat || c.includes(acctCat);
      return false;
    });
  }, [txns, account, periodMonths, hasPeriod]);

  // Build monthly totals — columns follow the selected period so the panel
  // shows exactly the period's months (e.g. 3 for QTD). When no global period
  // is set, fall back to the months the transactions actually span.
  const monthlyTotals = useMemo(() => {
    let columns = hasPeriod ? periodMonths.slice() : [];
    if (columns.length === 0) {
      const seen = new Set();
      acctTxns.forEach(t => { const m = (t.posted_date||t.date||'').slice(0,7); if (m) seen.add(m); });
      columns = [...seen].sort().slice(-13);
    }
    return columns.map(m => {
      const amount = acctTxns
        .filter(t => (t.posted_date||t.date||'').slice(0,7) === m)
        .reduce((s,t) => s + Math.abs(parseFloat(t.amount||0)), 0);
      return { month: m, amount };
    });
  }, [acctTxns, periodMonths, hasPeriod]);

  const total   = monthlyTotals.reduce((s,r) => s+r.amount, 0);
  const avgMo   = monthlyTotals.length > 0 ? total/monthlyTotals.length : 0;
  const peak    = monthlyTotals.reduce((p,r) => r.amount>p.amount?r:p, {month:'—',amount:0});
  const last    = monthlyTotals[monthlyTotals.length-1]?.amount || 0;
  const prev    = monthlyTotals[monthlyTotals.length-2]?.amount || 0;
  const trend   = prev > 0 ? ((last-prev)/prev*100).toFixed(1) : null;
  const maxAmt  = Math.max(...monthlyTotals.map(r=>r.amount), 1);

  const F = window.PerduraFormat;
  const fmt  = v => F ? F.money(Math.abs(v), { compact:true }) : (v>=1000000?'$'+(v/1e6).toFixed(2)+'M':v>=1000?'$'+Math.round(v/1000)+'K':'$'+Math.round(v));
  const fmtM = m => { try{ const d=new Date(m+'-02'); return d.toLocaleDateString('en-US',{month:'short',year:'2-digit'}); }catch(e){return m;} };

  if (!account) return null;

  // Empty state — no individual transactions match. Common for computed rows
  // (Gross Profit, EBITDA, ratios) that aren't a direct GL posting.
  if (acctTxns.length === 0) {
    return h('div', null,
      h('div', { onClick:onClose, style:{ position:'fixed',inset:0,background:'rgba(0,0,0,.35)',zIndex:998 } }),
      h('div', { style:{ position:'fixed',top:0,right:0,bottom:0,width:'500px',maxWidth:'100vw',background:'white',boxShadow:'-4px 0 32px rgba(0,0,0,.18)',zIndex:999,display:'flex',flexDirection:'column' } },
        h('div', { style:{ background:'#0d2040',padding:'16px 22px',display:'flex',justifyContent:'space-between',alignItems:'center',flexShrink:0 } },
          h('div', null,
            h('div', { style:{ color:'rgba(255,255,255,.5)',fontSize:'10px',fontWeight:'700',textTransform:'uppercase',letterSpacing:'.1em',marginBottom:'3px' } }, account.category || 'Account'),
            h('div', { style:{ color:'white',fontWeight:'800',fontSize:'16px' } }, account.name || 'Account')
          ),
          h('button', { onClick:onClose, style:{ background:'rgba(255,255,255,.15)',border:'none',color:'white',width:'30px',height:'30px',borderRadius:'50%',cursor:'pointer',fontSize:'18px',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 } }, '×')
        ),
        h('div', { style:{ flex:1,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'40px',textAlign:'center' } },
          h('div', { style:{ fontSize:'32px',marginBottom:'16px' } }, '🔍'),
          h('div', { style:{ fontSize:'14px',fontWeight:'700',color:'#0d2040',marginBottom:'8px' } }, 'No transactions found'),
          h('div', { style:{ fontSize:'12px',color:'#6475a0',lineHeight:'1.6',marginBottom:'20px' } },
            `No individual transactions match "${account.name}" in the selected period. This may be a computed metric (like Gross Profit or EBITDA) derived from multiple accounts rather than a direct GL posting.`),
          h('div', { style:{ background:'#f0f4ff',border:'1px solid rgba(28,78,216,.15)',borderRadius:'8px',padding:'12px 16px',fontSize:'11px',color:'#1C4ED8',textAlign:'left' } },
            h('div', { style:{ fontWeight:'700',marginBottom:'6px' } }, '💡 What to do:'),
            h('div', null, '• Go to the Income Statement page and expand the relevant section'),
            h('div', null, '• Click individual account rows (not subtotals) to see transactions'),
            h('div', null, '• Use the Expenses or Revenue page for detailed breakdowns')
          )
        )
      )
    );
  }

  return h('div', null,
    // Backdrop
    h('div', { onClick:onClose, style:{ position:'fixed',inset:0,background:'rgba(0,0,0,.35)',zIndex:999 } }),

    // Panel
    h('div', { style:{ position:'fixed',top:0,right:0,bottom:0,width:'640px',maxWidth:'100vw',background:'white',boxShadow:'-4px 0 32px rgba(0,0,0,.18)',zIndex:1000,display:'flex',flexDirection:'column',overflowY:'auto' } },

      // Header
      h('div', { style:{ background:'#0d2040',padding:'18px 22px',display:'flex',justifyContent:'space-between',alignItems:'flex-start',flexShrink:0 } },
        h('div', null,
          h('div', { style:{ color:'rgba(255,255,255,.55)',fontSize:'10px',fontWeight:'700',letterSpacing:'.1em',textTransform:'uppercase',marginBottom:'4px' } },
            account.category || 'Account Detail'
          ),
          h('div', { style:{ color:'white',fontWeight:'800',fontSize:'16px',lineHeight:'1.3' } }, account.name || 'Account'),
          h('div', { style:{ color:'rgba(255,255,255,.55)',fontSize:'11px',marginTop:'4px' } },
            `${acctTxns.length} transactions · ${periodLabel.toUpperCase()} · ${monthlyTotals.length} months`
          )
        ),
        h('button', { onClick:onClose, style:{ background:'rgba(255,255,255,.15)',border:'none',color:'white',width:'30px',height:'30px',borderRadius:'50%',cursor:'pointer',fontSize:'18px',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 } }, '×')
      ),

      // KPI strip
      h('div', { style:{ display:'flex',gap:'1px',background:'rgba(13,32,64,.08)',flexShrink:0 } },
        [
          { label:'Total (period)', value:fmt(total) },
          { label:'Monthly avg',    value:fmt(avgMo) },
          { label:'Peak month',     value:fmtM(peak.month)+' '+fmt(peak.amount) },
          { label:'vs Prior month', value: trend ? (trend>0?'+':'')+trend+'%' : '—',
            color: trend ? (parseFloat(trend)>0?'#d94f47':'#18a867') : '#6475a0' },
        ].map((kpi,i) => h('div', { key:i, style:{ flex:1,background:'white',padding:'14px 16px' } },
          h('div', { style:{ fontSize:'9px',fontWeight:'700',color:'#6475a0',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:'4px' } }, kpi.label),
          h('div', { style:{ fontSize:'14px',fontWeight:'800',color:kpi.color||'#0d2040',fontFamily:'JetBrains Mono,monospace' } }, kpi.value)
        ))
      ),

      // ── V2 analysis block (savings-style drill) — opt-in via ?v2shell=1 ──
      v2 && monthlyTotals.length > 0 && h('div', { style:{ display:'flex',borderBottom:'1px solid rgba(13,32,64,.08)',flexShrink:0 } },
        // LEFT: monthly spend breakdown (green below avg, red above avg)
        h('div', { style:{ flex:1,padding:'20px 22px' } },
          h('div', { style:{ fontSize:'10px',fontWeight:'700',color:'#6475a0',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:'12px' } }, 'Monthly Spend Breakdown'),
          monthlyTotals.map((r,i) => {
            const aboveAvg = r.amount > avgMo * 1.1;
            const barPct = maxAmt > 0 ? (r.amount/maxAmt*100) : 0;
            const prevAmt = i > 0 ? monthlyTotals[i-1].amount : r.amount;
            const chg = prevAmt > 0 ? ((r.amount-prevAmt)/prevAmt*100).toFixed(0) : '0';
            return h('div', { key:r.month, style:{ display:'flex',alignItems:'center',gap:'8px',marginBottom:'6px' } },
              h('div', { style:{ width:'48px',fontSize:'10px',color:'#6475a0',flexShrink:0 } }, fmtM(r.month)),
              h('div', { style:{ flex:1,height:'20px',background:'#f0f4ff',borderRadius:'3px',overflow:'hidden' } },
                h('div', { style:{ width:barPct+'%',height:'100%',background:aboveAvg?'#e74c3c':'#00b894',borderRadius:'3px',transition:'width .4s' } })),
              h('div', { style:{ width:'52px',fontSize:'10px',fontWeight:'600',color:'#1a2540',textAlign:'right',flexShrink:0,fontFamily:'JetBrains Mono,monospace' } }, fmt(r.amount)),
              h('div', { style:{ width:'38px',fontSize:'9px',color:parseFloat(chg)>10?'#e74c3c':'#00b894',textAlign:'right',flexShrink:0 } },
                i > 0 ? (parseFloat(chg)>0?'↑':'↓')+Math.abs(chg)+'%' : ''));
          })
        ),
        // RIGHT: why this matters + how to improve + summary strip
        h('div', { style:{ width:'260px',padding:'20px 22px',borderLeft:'1px solid rgba(13,32,64,.08)',flexShrink:0 } },
          h('div', { style:{ fontSize:'10px',fontWeight:'700',color:'#6475a0',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:'8px' } }, 'Why This Matters'),
          h('div', { style:{ fontSize:'11.5px',color:'#1a2540',lineHeight:'1.6',marginBottom:'16px' } },
            generateWhyItMatters(account.name, account.category, monthlyTotals, avgMo)),
          h('div', { style:{ fontSize:'10px',fontWeight:'700',color:'#6475a0',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:'8px' } }, 'How To Improve'),
          h('ul', { style:{ margin:0,padding:'0 0 0 14px' } },
            generateHowToImprove(account.name, account.category).map((tip,i) =>
              h('li', { key:i, style:{ fontSize:'11px',color:'#4a5680',marginBottom:'5px',lineHeight:'1.5' } }, tip))),
          h('div', { style:{ display:'flex',gap:'1px',background:'rgba(13,32,64,.06)',borderRadius:'8px',overflow:'hidden',marginTop:'20px' } },
            [
              { label:'Period Spend', value:fmt(total) },
              { label:'Monthly Avg', value:fmt(avgMo) },
              { label:'Trend', value: trend ? (parseFloat(trend)>0?'↑ ':'↓ ')+Math.abs(trend)+'%' : '—',
                color: trend ? (parseFloat(trend)>10?'#e74c3c':'#00b894') : '#6475a0' },
            ].map((s,i) => h('div', { key:i, style:{ flex:1,padding:'10px 8px',background:'white',textAlign:'center' } },
              h('div', { style:{ fontSize:'9px',fontWeight:'700',color:'#6475a0',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:'3px' } }, s.label),
              h('div', { style:{ fontSize:'12px',fontWeight:'800',color:s.color||'#0d2040',fontFamily:'JetBrains Mono,monospace' } }, s.value))))
        )
      ),

      // Monthly bar chart
      h('div', { style:{ padding:'20px 22px 0',flexShrink:0 } },
        h('div', { style:{ fontSize:'10px',fontWeight:'700',color:'#6475a0',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:'12px' } }, 'Monthly Balance'),
        monthlyTotals.length === 0
          ? h('div', { style:{ fontSize:'12px',color:'#6475a0',padding:'8px 0 16px' } }, 'No dated transactions for this account.')
          : h('div', { style:{ display:'flex',alignItems:'flex-end',gap:'4px',height:'80px' } },
              monthlyTotals.map((r,i) => {
                const isLast = i === monthlyTotals.length-1;
                const pct = maxAmt > 0 ? r.amount/maxAmt : 0;
                return h('div', { key:r.month, style:{ flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:'4px' } },
                  h('div', { style:{ width:'100%',height:Math.max(3,Math.round(pct*70))+'px',background:isLast?'#1C4ED8':'rgba(13,32,64,.25)',borderRadius:'3px 3px 0 0',transition:'height .3s' } }),
                  h('div', { style:{ fontSize:'8px',color:'#6475a0',transform:'rotate(-45deg)',transformOrigin:'center',whiteSpace:'nowrap',marginTop:'4px' } }, fmtM(r.month))
                );
              })
            )
      ),

      // Monthly detail table
      h('div', { style:{ padding:'20px 22px',flexShrink:0 } },
        h('div', { style:{ fontSize:'10px',fontWeight:'700',color:'#6475a0',letterSpacing:'.08em',textTransform:'uppercase',marginBottom:'10px' } }, 'Monthly Detail'),
        h('table', { style:{ width:'100%',borderCollapse:'collapse',fontSize:'11.5px' } },
          h('thead', null,
            h('tr', null,
              ['Month','Amount','% of Total','vs Prior Month'].map(col =>
                h('th', { key:col, style:{ textAlign:col==='Month'?'left':'right',padding:'7px 10px',background:'#0d2040',color:'white',fontWeight:'700',fontSize:'10px',textTransform:'uppercase',letterSpacing:'.05em' } }, col)
              )
            )
          ),
          h('tbody', null,
            [...monthlyTotals].reverse().map((r,i) => {
              const priorIdx = monthlyTotals.length - 1 - i - 1;
              const prior = priorIdx >= 0 ? monthlyTotals[priorIdx].amount : null;
              const chg = prior && prior > 0 ? ((r.amount-prior)/prior*100).toFixed(1) : null;
              const pctTotal = total > 0 ? (r.amount/total*100).toFixed(1) : '0.0';
              const isLatest = i === 0;
              return h('tr', { key:r.month, style:{ background:isLatest?'rgba(28,78,216,.04)':i%2===0?'white':'rgba(248,249,252,1)',borderBottom:'1px solid rgba(13,32,64,.05)' } },
                h('td', { style:{ padding:'7px 10px',fontWeight:isLatest?'700':'400',color:'#0d2040' } }, fmtM(r.month)+(isLatest?' ★':'')),
                h('td', { style:{ padding:'7px 10px',textAlign:'right',fontFamily:'JetBrains Mono,monospace',fontWeight:isLatest?'800':'500',color:'#0d2040' } }, fmt(r.amount)),
                h('td', { style:{ padding:'7px 10px',textAlign:'right',color:'#6475a0',fontSize:'11px' } }, pctTotal+'%'),
                h('td', { style:{ padding:'7px 10px',textAlign:'right',fontFamily:'JetBrains Mono,monospace',fontSize:'11px',color:chg===null?'#bbb':parseFloat(chg)>0?'#d94f47':'#18a867' } },
                  chg===null ? '—' : (parseFloat(chg)>0?'▲ +':'▼ ')+chg+'%'
                )
              );
            })
          )
        )
      ),

      // View transactions button
      h('div', { style:{ padding:'0 22px 24px',flexShrink:0,marginTop:'auto' } },
        h('button', {
          onClick: () => onViewTransactions && onViewTransactions({ accountName: account.name, category: account.category }),
          style:{ width:'100%',padding:'12px',background:'#0d2040',color:'white',border:'none',borderRadius:'9px',fontSize:'13px',fontWeight:'700',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',gap:'8px' }
        }, '→ View Raw Transactions (' + acctTxns.length + ')')
      )
    )
  );
}

window.AccountDetailPanel = AccountDetailPanel;
})();
