// V4 — Editorial / modular
// Section headings live OUTSIDE cards (magazine style). One featured pace
// card with a larger chart, then a 2-col KPI grid, then mixed-size insight
// cards. More whitespace, less repetition of card chrome.

function DashV4Header() {
  return (
    <div style={{ padding: '14px 20px 8px', background: RVU.bg }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            width: 10, height: 10, borderRadius: 999, background: RVU.tealDeep,
            boxShadow: `0 0 0 4px ${RVU.teal}22`,
          }}/>
          <span style={{ fontSize: 11, fontWeight: 600, color: RVU.textSec, letterSpacing: 0.4 }}>
            Logged today · 23.86 wRVUs
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <div style={{ padding: 6 }}><Icon.share/></div>
          <div style={{ padding: 6 }}><Icon.gear/></div>
        </div>
      </div>
      <div style={{ marginTop: 8, fontSize: 32, fontWeight: 700, color: RVU.navyDark, letterSpacing: -0.8, lineHeight: 1.05 }}>
        My Tracker
      </div>
      <div style={{ fontSize: 12, color: RVU.textMuted, marginTop: 4 }}>
        {MOCK.profile.feeYear} fee schedule · {MOCK.profile.localityName}
      </div>
    </div>
  );
}

function DashV4Featured() {
  const { stats, profile } = MOCK;
  const W = 340, H = 150, PAD = 8;
  const goal = profile.annualGoal;
  const x = (t) => PAD + t * (W - PAD * 2);
  const y = (v) => H - PAD - (v / goal) * (H - PAD * 2);
  const userPath = stats.paceCurve.map((p, i) =>
    (i === 0 ? 'M' : 'L') + x(p[0]) + ' ' + y(p[1] * goal)
  ).join(' ');
  const last = stats.paceCurve[stats.paceCurve.length - 1];

  return (
    <div style={{
      background: RVU.surface, borderRadius: 20,
      border: `1px solid ${RVU.border}`,
      padding: '20px 20px 16px', margin: '0 16px 14px',
      boxShadow: '0 1px 3px rgba(15,43,91,0.04)',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 11, color: RVU.textMuted, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>
            wRVUs logged · YTD
          </div>
          <div style={{
            fontFamily: RVU.fontNum, fontSize: 44, fontWeight: 700,
            color: RVU.navyDark, lineHeight: 1, letterSpacing: -1.6,
            fontVariantNumeric: 'tabular-nums', marginTop: 6,
          }}>
            {fmt.rvu(stats.totalWRVU)}
          </div>
          <div style={{ fontSize: 12, color: RVU.textSec, marginTop: 6 }}>
            <span style={{ fontWeight: 600, color: RVU.navyDark }}>{fmt.pct(stats.progress)}</span> of {fmt.rvu0(profile.annualGoal).toLocaleString()} goal
          </div>
        </div>
        <div style={{
          display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2,
        }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '4px 10px', borderRadius: 999, background: RVU.teal + '22',
          }}>
            <Icon.arrowUp c={RVU.tealDeep} s={11}/>
            <span style={{ fontSize: 12, fontWeight: 700, color: RVU.tealDeep, fontVariantNumeric: 'tabular-nums' }}>
              +{(stats.pacePct * 100).toFixed(1)}%
            </span>
          </div>
          <span style={{ fontSize: 10.5, color: RVU.textMuted, marginTop: 2 }}>ahead of pace</span>
        </div>
      </div>

      {/* Big pace chart */}
      <div style={{ marginTop: 16 }}>
        <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
          <defs>
            <linearGradient id="v4area" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"   stopColor={RVU.navy} stopOpacity="0.22"/>
              <stop offset="100%" stopColor={RVU.navy} stopOpacity="0"/>
            </linearGradient>
          </defs>
          {/* gridlines */}
          {[0.25, 0.5, 0.75].map(t => (
            <line key={t} x1={PAD} x2={W-PAD} y1={y(goal*t)} y2={y(goal*t)}
                  stroke={RVU.borderLt} strokeWidth={1}/>
          ))}
          {/* goal */}
          <line x1={x(0)} y1={y(0)} x2={x(1)} y2={y(goal)} stroke={RVU.textMuted} strokeWidth={1.2} strokeDasharray="4 4"/>
          {/* user */}
          <path d={userPath + ` L${x(last[0])} ${y(0)} L${x(0)} ${y(0)} Z`} fill="url(#v4area)"/>
          <path d={userPath} stroke={RVU.navy} strokeWidth={2.4} fill="none" strokeLinejoin="round" strokeLinecap="round"/>
          {/* end pulse */}
          <circle cx={x(last[0])} cy={y(last[1] * goal)} r={10} fill={RVU.tealDeep} fillOpacity="0.15"/>
          <circle cx={x(last[0])} cy={y(last[1] * goal)} r={4.5} fill={RVU.tealDeep}/>
          {/* labels at edges */}
          <text x={x(0)} y={y(goal)-4} fontSize="9" fill={RVU.textMuted} fontFamily={RVU.fontMono}>{goal.toLocaleString()}</text>
          {['Jan','Mar','May','Jul','Sep','Nov'].map((m, i) => (
            <text key={m} x={x(i / 5)} y={H-1} fontSize="9" fill={RVU.textMuted} textAnchor="middle" fontFamily={RVU.fontMono}>{m}</text>
          ))}
        </svg>
      </div>

      <div style={{
        marginTop: 12, paddingTop: 14, borderTop: `1px solid ${RVU.borderLt}`,
        display: 'flex', justifyContent: 'space-between',
      }}>
        <V4FeaturedStat label="Projected" value={fmt.rvu0(stats.projectedYearEnd)} sub="year-end"/>
        <V4FeaturedStat label="Need/day" value={fmt.rvu1(stats.rvuPerWorkDayNeeded)} sub={`${stats.workDaysRemaining} days`}/>
        <V4FeaturedStat label="Avg/day" value={fmt.rvu1(stats.avgPerDay)} sub="118 days"/>
      </div>
    </div>
  );
}
function V4FeaturedStat({ label, value, sub }) {
  return (
    <div>
      <div style={{ fontSize: 10, color: RVU.textMuted, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 4 }}>{label}</div>
      <div style={{
        fontFamily: RVU.fontNum, fontSize: 17, fontWeight: 700, color: RVU.navyDark,
        fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3, lineHeight: 1,
      }}>{value}</div>
      <div style={{ fontSize: 10, color: RVU.textMuted, marginTop: 3 }}>{sub}</div>
    </div>
  );
}

function DashV4SectionTitle({ overline, title, action }) {
  return (
    <div style={{ padding: '4px 20px 10px' }}>
      <div style={{
        fontSize: 10.5, color: RVU.tealDeep, fontWeight: 700,
        textTransform: 'uppercase', letterSpacing: 1, marginBottom: 4,
      }}>{overline}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 18, fontWeight: 700, color: RVU.navyDark, letterSpacing: -0.4 }}>{title}</span>
        {action && <span style={{ fontSize: 12, color: RVU.navy, fontWeight: 600 }}>{action}</span>}
      </div>
    </div>
  );
}

function DashV4MonthlyCard() {
  const data = MOCK.stats.monthly;
  const max = Math.max(...data.map(d => d.v));
  return (
    <div style={{
      background: RVU.surface, borderRadius: 18,
      border: `1px solid ${RVU.border}`,
      padding: 18, margin: '0 16px 12px',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: RVU.navyDark }}>Monthly wRVU</span>
        <span style={{ fontSize: 11, color: RVU.textMuted, fontFamily: RVU.fontMono }}>5 months · avg 636</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 100 }}>
        {data.map((b, i) => {
          const h = (b.v / max) * 82;
          const isCurrent = i === 4;
          const isFuture = b.v === 0;
          return (
            <div key={b.m} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
              <div style={{
                width: '100%', height: Math.max(h, isFuture ? 3 : 3),
                borderRadius: 4,
                background: isFuture ? RVU.borderLt : (isCurrent ? RVU.teal : RVU.navy),
                opacity: isFuture ? 0.6 : 1,
              }}/>
              <div style={{ fontSize: 10, color: isCurrent ? RVU.navyDark : RVU.textMuted, fontWeight: isCurrent ? 600 : 400 }}>
                {b.m}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DashV4Duet() {
  const { newPt, estPt } = MOCK.stats.visitTypes;
  const data = MOCK.stats.careMix;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, margin: '0 16px 12px' }}>
      {/* Visit mix card */}
      <div style={{
        background: RVU.surface, borderRadius: 18, border: `1px solid ${RVU.border}`,
        padding: 16,
      }}>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: RVU.navyDark, marginBottom: 10 }}>Visits</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <V4VisitBlock color={RVU.teal} label="New"          count={newPt.ytdCount} rvu={newPt.ytdRVU}/>
          <V4VisitBlock color={RVU.navy} label="Established"  count={estPt.ytdCount} rvu={estPt.ytdRVU}/>
        </div>
      </div>
      {/* Care setting */}
      <div style={{
        background: RVU.surface, borderRadius: 18, border: `1px solid ${RVU.border}`,
        padding: 16,
      }}>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: RVU.navyDark, marginBottom: 10 }}>Care setting</div>
        {/* mini donut */}
        <V4Donut data={data}/>
      </div>
    </div>
  );
}
function V4VisitBlock({ color, label, count, rvu }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
        <div style={{ width: 6, height: 6, background: color, borderRadius: 999 }}/>
        <span style={{ fontSize: 10.5, color: RVU.textSec, fontWeight: 500 }}>{label}</span>
      </div>
      <div style={{
        fontFamily: RVU.fontNum, fontSize: 22, fontWeight: 700,
        color: RVU.navyDark, lineHeight: 1, letterSpacing: -0.5,
        fontVariantNumeric: 'tabular-nums',
      }}>{count}</div>
      <div style={{ fontSize: 10, color: RVU.textMuted, marginTop: 2, fontFamily: RVU.fontMono }}>
        {fmt.rvu1(rvu)} wRVUs
      </div>
    </div>
  );
}

function V4Donut({ data }) {
  const R = 38, CX = 42, CY = 42, sw = 14;
  let cum = 0;
  const C = 2 * Math.PI * R;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <svg width="84" height="84" viewBox="0 0 84 84" style={{ flexShrink: 0 }}>
        <circle cx={CX} cy={CY} r={R} stroke={RVU.borderLt} strokeWidth={sw} fill="none"/>
        {data.map((d, i) => {
          const dash = d.pct * C;
          const offset = -cum * C;
          cum += d.pct;
          const el = (
            <circle key={i} cx={CX} cy={CY} r={R}
                    stroke={d.color} strokeWidth={sw} fill="none"
                    strokeDasharray={`${dash} ${C - dash}`}
                    strokeDashoffset={offset}
                    transform={`rotate(-90 ${CX} ${CY})`}/>
          );
          return el;
        })}
      </svg>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1, minWidth: 0 }}>
        {data.map(d => (
          <div key={d.label} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <div style={{ width: 6, height: 6, background: d.color, borderRadius: 999, flexShrink: 0 }}/>
            <span style={{ fontSize: 10, color: RVU.textSec, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.label}</span>
            <span style={{ fontSize: 10, fontWeight: 700, color: RVU.navyDark, fontFamily: RVU.fontMono }}>{fmt.pct0(d.pct)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function DashV4TopCodes() {
  const codes = MOCK.stats.topCodes;
  const max = Math.max(...codes.map(c => c.total));
  return (
    <div style={{
      background: RVU.surface, borderRadius: 18, border: `1px solid ${RVU.border}`,
      padding: '14px 18px', margin: '0 16px 12px',
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: RVU.navyDark }}>Top codes</span>
        <span style={{ fontSize: 11, color: RVU.navy, fontWeight: 600 }}>Search →</span>
      </div>
      {codes.slice(0, 5).map((c, i) => (
        <div key={c.code} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '8px 0',
          borderTop: i > 0 ? `1px solid ${RVU.borderLt}` : 'none',
        }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: RVU.navyDark, fontFamily: RVU.fontMono, width: 44 }}>
            {c.code}
          </span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11.5, color: RVU.textSec, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.desc}</div>
            <div style={{ height: 3, background: RVU.borderLt, borderRadius: 999, marginTop: 4 }}>
              <div style={{ width: `${(c.total / max) * 100}%`, height: '100%', background: RVU.navyLight, borderRadius: 999 }}/>
            </div>
          </div>
          <span style={{ fontSize: 11, fontWeight: 700, color: RVU.navyDark, fontFamily: RVU.fontMono, fontVariantNumeric: 'tabular-nums', minWidth: 50, textAlign: 'right' }}>
            {fmt.rvu(c.total)}
          </span>
        </div>
      ))}
    </div>
  );
}

function DashV4Log() {
  const days = MOCK.encounterDays;
  return (
    <div style={{ margin: '0 16px' }}>
      {days.map((day, di) => (
        <div key={di} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 4px 8px' }}>
            <div>
              <div style={{ fontSize: 11, color: RVU.tealDeep, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>
                {day.date.split(',')[0]}
              </div>
              <div style={{ fontSize: 16, fontWeight: 700, color: RVU.navyDark, letterSpacing: -0.3 }}>
                {day.date.split(',')[1].trim()}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{
                fontFamily: RVU.fontNum, fontSize: 18, fontWeight: 700, color: RVU.navyDark,
                fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3,
              }}>{fmt.rvu(day.total)}</div>
              <div style={{ fontSize: 10, color: RVU.textMuted, fontFamily: RVU.fontMono }}>wRVUs · {day.rows.length} enc</div>
            </div>
          </div>
          <div style={{
            background: RVU.surface, borderRadius: 14,
            border: `1px solid ${RVU.border}`, overflow: 'hidden',
          }}>
            {day.rows.map((r, ri) => (
              <div key={ri} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
                borderBottom: ri < day.rows.length - 1 ? `1px solid ${RVU.borderLt}` : 'none',
              }}>
                <span style={{ fontSize: 11.5, fontWeight: 700, color: RVU.navyDark, fontFamily: RVU.fontMono, minWidth: 48 }}>
                  {r.code}
                </span>
                <span style={{ flex: 1, fontSize: 12, color: RVU.textSec, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {r.desc}
                </span>
                <span style={{ fontSize: 12, fontWeight: 700, color: RVU.navy, fontFamily: RVU.fontMono, fontVariantNumeric: 'tabular-nums' }}>
                  {fmt.rvu(r.rvu)}
                </span>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function DashboardV4() {
  return (
    <PhoneShell>
      <DashV4Header/>
      <div style={{ height: 12 }}/>
      <DashV4Featured/>

      <div style={{ marginTop: 10 }}>
        <DashV4SectionTitle overline="Insights" title="This year so far" action="View all"/>
        <DashV4MonthlyCard/>
        <DashV4Duet/>
        <DashV4TopCodes/>
      </div>

      <div style={{ marginTop: 10 }}>
        <DashV4SectionTitle overline="Log" title="Recent encounters" action="118 →"/>
        <DashV4Log/>
      </div>

      <div style={{ height: 16 }}/>
      <TabBar/>
    </PhoneShell>
  );
}

window.DashboardV4 = DashboardV4;
