// Analytics+ — Source attribution · Cohort analysis · Deal velocity · Win/Loss

function BarChart({ data, colorKey }) {
  const max = Math.max(...data.map(d=>d.value), 1);
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
      {data.map((d,i) => (
        <div key={i} style={{ display:'grid', gridTemplateColumns:'130px 1fr 50px', alignItems:'center', gap:10 }}>
          <div style={{ fontSize:12.5, color:'var(--ink-2)', fontWeight:500, textAlign:'right', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{d.label}</div>
          <div style={{ height:8, background:'var(--border)', borderRadius:99, overflow:'hidden' }}>
            <div style={{ width:(d.value/max*100)+'%', height:'100%', background: colorKey ? d[colorKey] || 'var(--accent)' : 'var(--accent)', borderRadius:99, transition:'width 0.5s ease' }} />
          </div>
          <div style={{ fontSize:12, fontFamily:'var(--mono)', color:'var(--ink-3)', fontWeight:600 }}>{d.display || d.value}</div>
        </div>
      ))}
    </div>
  );
}

function AnalyticsPlus({ deals, reps }) {
  const [activeTab, setActiveTab] = React.useState('attribution');

  // Source data
  const SOURCES = [
    { label:'Showroom walk-in', value:38, display:'38%', color:'var(--accent)' },
    { label:'Referral', value:26, display:'26%', color:'var(--won)' },
    { label:'Google / SEO', value:17, display:'17%', color:'var(--info)' },
    { label:'Facebook Ads', value:9, display:'9%', color:'#8B5CF6' },
    { label:'Repeat customer', value:6, display:'6%', color:'var(--warn)' },
    { label:'Other', value:4, display:'4%', color:'var(--ink-4)' },
  ];

  const WIN_RATES = [
    { label:'Showroom walk-in', value:41, display:'41%', color:'var(--won)' },
    { label:'Referral', value:58, display:'58%', color:'var(--won)' },
    { label:'Google / SEO', value:22, display:'22%', color:'var(--warn)' },
    { label:'Facebook Ads', value:15, display:'15%', color:'var(--warn)' },
    { label:'Repeat customer', value:72, display:'72%', color:'var(--won)' },
  ];

  // Cohort data (6 months)
  const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun'];
  const COHORT = [
    { month:'Jan 26', starts:24, m1:19, m2:14, m3:10, m4:7, m5:5 },
    { month:'Feb 26', starts:31, m1:24, m2:18, m3:13, m4:9, m5:null },
    { month:'Mar 26', starts:28, m1:22, m2:16, m3:11, m4:null, m5:null },
    { month:'Apr 26', starts:35, m1:27, m2:20, m3:null, m4:null, m5:null },
    { month:'May 26', starts:29, m1:23, m2:null, m3:null, m4:null, m5:null },
    { month:'Jun 26', starts:18, m1:null, m2:null, m3:null, m4:null, m5:null },
  ];

  // Velocity
  const STAGES_V = [
    { label:'Possible', count:62, avgDays:4.2, conversion:68 },
    { label:'In Progress', count:42, avgDays:18.4, conversion:55 },
    { label:'On Hold', count:14, avgDays:31.2, conversion:28 },
    { label:'Won', count:23, avgDays:null, conversion:null },
  ];

  // Win/Loss
  const LOSS_REASONS = [
    { label:'Price too high', value:31, display:'31%', color:'var(--lost)' },
    { label:'Chose competitor', value:24, display:'24%', color:'var(--warn)' },
    { label:'Project delayed', value:18, display:'18%', color:'#8B5CF6' },
    { label:'Budget reduced', value:14, display:'14%', color:'var(--info)' },
    { label:'Unresponsive', value:8, display:'8%', color:'var(--ink-3)' },
    { label:'Other', value:5, display:'5%', color:'var(--ink-4)' },
  ];

  const COMPETITORS = [
    { label:'Kaboodle (Bunnings)', value:28, display:'28%', color:'var(--lost)' },
    { label:'IKEA Kitchen', value:22, display:'22%', color:'var(--warn)' },
    { label:'Harvey Norman', value:18, display:'18%', color:'#8B5CF6' },
    { label:'Local independent', value:20, display:'20%', color:'var(--info)' },
    { label:'Unknown', value:12, display:'12%', color:'var(--ink-4)' },
  ];

  function cohortColor(pct) {
    if (pct == null) return { background:'var(--surface-2)', color:'var(--ink-4)' };
    if (pct >= 70) return { background:'#DCFCE7', color:'#15803D' };
    if (pct >= 50) return { background:'#D1FAE5', color:'#065F46' };
    if (pct >= 35) return { background:'#FEF3C7', color:'#92400E' };
    return { background:'#FEE2E2', color:'#991B1B' };
  }

  return (
    <div>
      <div style={{ display:'flex', gap:2, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, padding:3, marginBottom:18, width:'fit-content' }}>
        {[['attribution','Source Attribution'],['cohort','Cohort Analysis'],['velocity','Deal Velocity'],['winloss','Win & Loss']].map(([id,label]) => (
          <button key={id} onClick={() => setActiveTab(id)}
            style={{ padding:'5px 16px', borderRadius:6, border:'none', fontSize:13, fontWeight:activeTab===id?600:400,
              background: activeTab===id ? 'var(--surface)' : 'transparent',
              color: activeTab===id ? 'var(--ink)' : 'var(--ink-3)',
              boxShadow: activeTab===id ? 'var(--shadow-sm)' : 'none', cursor:'pointer', whiteSpace:'nowrap' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── Source Attribution ── */}
      {activeTab === 'attribution' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div className="card">
            <div className="card-hd"><div className="card-title">Lead Sources</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Last 90 days</span></div>
            <div style={{ padding:'18px 20px' }}>
              <BarChart data={SOURCES} colorKey="color" />
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><div className="card-title">Win Rate by Source</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Deals closed / leads generated</span></div>
            <div style={{ padding:'18px 20px' }}>
              <BarChart data={WIN_RATES} colorKey="color" />
              <div style={{ marginTop:14, padding:'10px 12px', background:'var(--won-soft)', borderRadius:6, fontSize:12.5, color:'var(--won)', lineHeight:1.6 }}>
                <strong>Referrals</strong> win at 58% — nearly 4× the rate of paid ads. Consider a referral incentive programme.
              </div>
            </div>
          </div>
          <div className="card" style={{ gridColumn:'1/-1' }}>
            <div className="card-hd"><div className="card-title">Revenue by Source</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Total closed value · last 6 months</span></div>
            <div style={{ padding:'18px 20px', display:'grid', gridTemplateColumns:'repeat(6,1fr)', gap:12 }}>
              {SOURCES.map((s,i) => {
                const revenue = [284000, 392000, 118000, 54000, 108000, 31000][i];
                return (
                  <div key={s.label} style={{ textAlign:'center', padding:'14px 10px', background:'var(--surface-2)', borderRadius:8 }}>
                    <div style={{ fontSize:11, color:'var(--ink-3)', marginBottom:6, fontWeight:600 }}>{s.label}</div>
                    <div style={{ fontSize:16, fontWeight:700, color:s.color, fontFamily:'var(--mono)' }}>${Math.round(revenue/1000)}k</div>
                    <div style={{ fontSize:11, color:'var(--ink-4)', marginTop:3 }}>{s.display} of leads</div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {/* ── Cohort Analysis ── */}
      {activeTab === 'cohort' && (
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <div className="card">
            <div className="card-hd">
              <div>
                <div className="card-title">Lead Retention Cohorts</div>
                <div className="card-sub">% of leads still active / progressing month over month</div>
              </div>
            </div>
            <div style={{ padding:'18px 20px', overflowX:'auto' }}>
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
                <thead>
                  <tr>
                    <th style={{ padding:'8px 14px', textAlign:'left', fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.04em', color:'var(--ink-3)', borderBottom:'2px solid var(--border)' }}>Cohort</th>
                    <th style={{ padding:'8px 14px', textAlign:'right', fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.04em', color:'var(--ink-3)', borderBottom:'2px solid var(--border)' }}>Starts</th>
                    {['Month 1','Month 2','Month 3','Month 4','Month 5'].map(m => (
                      <th key={m} style={{ padding:'8px 14px', textAlign:'center', fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.04em', color:'var(--ink-3)', borderBottom:'2px solid var(--border)', minWidth:80 }}>{m}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {COHORT.map((row, i) => {
                    const vals = [row.m1, row.m2, row.m3, row.m4, row.m5];
                    return (
                      <tr key={i} style={{ borderBottom:'1px solid var(--border)' }}>
                        <td style={{ padding:'10px 14px', fontWeight:600, color:'var(--ink)' }}>{row.month}</td>
                        <td style={{ padding:'10px 14px', textAlign:'right', fontFamily:'var(--mono)', color:'var(--ink-3)', fontWeight:600 }}>{row.starts}</td>
                        {vals.map((v, j) => {
                          const pct = v != null ? Math.round(v / row.starts * 100) : null;
                          const style = cohortColor(pct);
                          return (
                            <td key={j} style={{ padding:'8px 14px', textAlign:'center' }}>
                              {pct != null ? (
                                <span style={{ ...style, borderRadius:6, padding:'4px 10px', fontSize:12.5, fontWeight:700, display:'inline-block', minWidth:48 }}>
                                  {pct}%
                                </span>
                              ) : (
                                <span style={{ color:'var(--ink-4)', fontSize:12 }}>—</span>
                              )}
                            </td>
                          );
                        })}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              <div style={{ marginTop:12, display:'flex', gap:10, flexWrap:'wrap' }}>
                {[['≥70%','#DCFCE7','#15803D'],['50–69%','#D1FAE5','#065F46'],['35–49%','#FEF3C7','#92400E'],['<35%','#FEE2E2','#991B1B']].map(([l,bg,c]) => (
                  <span key={l} style={{ fontSize:11, padding:'2px 8px', borderRadius:4, background:bg, color:c, fontWeight:600 }}>{l}</span>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Deal Velocity ── */}
      {activeTab === 'velocity' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div className="card">
            <div className="card-hd"><div className="card-title">Pipeline Funnel</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Current counts by stage</span></div>
            <div style={{ padding:'24px 20px', display:'flex', flexDirection:'column', gap:10 }}>
              {STAGES_V.map((s,i) => {
                const width = [100, 68, 23, 37][i];
                return (
                  <div key={s.label}>
                    <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5, fontSize:12.5 }}>
                      <span style={{ fontWeight:600, color:'var(--ink)' }}>{s.label}</span>
                      <span style={{ color:'var(--ink-3)', fontFamily:'var(--mono)' }}>{s.count} deals{s.avgDays ? ` · avg ${s.avgDays}d` : ''}</span>
                    </div>
                    <div style={{ height:22, background:'var(--surface-2)', borderRadius:4, overflow:'hidden' }}>
                      <div style={{ width:width+'%', height:'100%', background:['var(--s-possible)','var(--s-in_progress)','var(--s-on_hold)','var(--won)'][i], borderRadius:4, display:'flex', alignItems:'center', paddingLeft:8, fontSize:11, color:'white', fontWeight:600 }}>
                        {s.conversion ? s.conversion+'%' : ''}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><div className="card-title">Average Days per Stage</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Cycle time analysis</span></div>
            <div style={{ padding:'18px 20px', display:'flex', flexDirection:'column', gap:12 }}>
              {STAGES_V.filter(s=>s.avgDays).map(s => (
                <div key={s.label}>
                  <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4, fontSize:12.5 }}>
                    <span style={{ fontWeight:500, color:'var(--ink-2)' }}>{s.label}</span>
                    <span style={{ fontFamily:'var(--mono)', fontWeight:700, color:'var(--ink)' }}>{s.avgDays}d avg</span>
                  </div>
                  <div style={{ height:6, background:'var(--border)', borderRadius:99 }}>
                    <div style={{ width:Math.min(s.avgDays/35*100,100)+'%', height:'100%', background: s.avgDays > 25 ? 'var(--warn)' : 'var(--accent)', borderRadius:99 }} />
                  </div>
                </div>
              ))}
              <div style={{ marginTop:8, padding:'10px 12px', background:'var(--warn-soft)', borderRadius:6, fontSize:12.5, color:'var(--warn)', lineHeight:1.6 }}>
                Deals in <strong>On Hold</strong> average 31 days — set an automation to alert reps after 14 days.
              </div>
            </div>
          </div>
          <div className="card" style={{ gridColumn:'1/-1' }}>
            <div className="card-hd"><div className="card-title">Rep Velocity Comparison</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Average deal cycle days per rep</span></div>
            <div style={{ padding:'18px 20px' }}>
              <BarChart data={reps.slice(0,6).map((r,i) => ({ label:r.name, value:[19,23,28,15,31,21][i]||22, display:[19,23,28,15,31,21][i]+'d', color: [19,23,28,15,31,21][i] < 22 ? 'var(--won)' : 'var(--warn)' }))} colorKey="color" />
            </div>
          </div>
        </div>
      )}

      {/* ── Win & Loss ── */}
      {activeTab === 'winloss' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div className="card">
            <div className="card-hd"><div className="card-title">Loss Reasons</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Last 90 days · {LOSS_REASONS.reduce((a,r)=>a+r.value,0)} losses</span></div>
            <div style={{ padding:'18px 20px' }}>
              <BarChart data={LOSS_REASONS} colorKey="color" />
              <div style={{ marginTop:14, padding:'10px 12px', background:'var(--lost-soft)', borderRadius:6, fontSize:12.5, color:'var(--lost)', lineHeight:1.6 }}>
                <strong>Price</strong> is the #1 loss reason. Review your pricing vs. Kaboodle and Harvey Norman on high-volume SKUs.
              </div>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><div className="card-title">Lost to Competitors</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Deals where competitor was named</span></div>
            <div style={{ padding:'18px 20px' }}>
              <BarChart data={COMPETITORS} colorKey="color" />
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><div className="card-title">Win Rate Trend</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Monthly</span></div>
            <div style={{ padding:'18px 20px' }}>
              {['Jan','Feb','Mar','Apr','May','Jun'].map((m,i) => {
                const rates = [31,34,29,38,41,39];
                return (
                  <div key={m} style={{ display:'grid', gridTemplateColumns:'40px 1fr 44px', alignItems:'center', gap:10, marginBottom:8 }}>
                    <span style={{ fontSize:12, color:'var(--ink-3)', fontWeight:500 }}>{m}</span>
                    <div style={{ height:7, background:'var(--border)', borderRadius:99, overflow:'hidden' }}>
                      <div style={{ width:rates[i]+'%', height:'100%', background: rates[i] >= 38 ? 'var(--won)' : 'var(--accent)', borderRadius:99 }} />
                    </div>
                    <span style={{ fontSize:12, fontFamily:'var(--mono)', fontWeight:700, color: rates[i] >= 38 ? 'var(--won)' : 'var(--ink-3)' }}>{rates[i]}%</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><div className="card-title">Summary KPIs</div></div>
            <div style={{ padding:'18px 20px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
              {[
                { label:'Overall Win Rate', value:'39%', delta:'+8%', up:true },
                { label:'Avg Won Value', value:'$68.4k', delta:'+12%', up:true },
                { label:'Avg Lost Value', value:'$41.2k', delta:'-3%', up:false },
                { label:'Days to Close', value:'24d', delta:'-4d', up:true },
              ].map(k => (
                <div key={k.label} style={{ padding:'12px 14px', background:'var(--surface-2)', borderRadius:8 }}>
                  <div style={{ fontSize:11, color:'var(--ink-3)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:6 }}>{k.label}</div>
                  <div style={{ fontSize:22, fontWeight:700, color:'var(--ink)', letterSpacing:'-0.02em', fontFamily:'var(--mono)' }}>{k.value}</div>
                  <div style={{ fontSize:12, color: k.up ? 'var(--won)' : 'var(--lost)', marginTop:3, fontWeight:500 }}>{k.delta} vs last quarter</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AnalyticsPlus = AnalyticsPlus;
