// Goal detail — full-screen view of a single milestone

function GoalDetailScreen({ theme, accent, goalId, onBack, onAskHimma }) {
  const goal = GOALS.find(g => g.id === goalId) || GOALS[0];
  const m = getGoalMetrics(goal);
  const linked = getGoalLinkedAccounts(goal);
  const Icon = Ico[goal.icon] || Ico.target;

  const isPayoff = goal.kind === 'payoff';
  const trajectory = buildGoalTrajectory(goal, m);
  const onPaceColor = m.onPace ? theme.positive : theme.warning;
  const projDate = m.projectedCompletionDate;
  const targetDate = m.targetDate;
  const projVsTarget = projDate && targetDate
    ? Math.round((projDate - targetDate) / (1000*60*60*24*30.44))
    : 0;

  return (
    <Screen theme={theme} padBottom={40}>
      {/* Header */}
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding: '18px 20px 12px',
      }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, borderRadius: 18,
          background: 'transparent', border: `0.5px solid ${theme.line2}`,
          color: theme.text, cursor: 'pointer',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}><Ico.chevL size={14}/></button>
        <div style={{ fontFamily: FONTS.mono, fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase', color: theme.textMute }}>
          {GOAL_KIND_LABELS[goal.kind]}
        </div>
        <button style={{
          width: 36, height: 36, borderRadius: 18,
          background: 'transparent', border: `0.5px solid ${theme.line2}`,
          color: theme.text, cursor: 'pointer',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}><Ico.dots size={14}/></button>
      </div>

      {/* Title */}
      <div style={{ padding: '0 22px 16px' }}>
        <div style={{ display:'flex', alignItems:'center', gap: 12 }}>
          <div style={{
            width: 40, height: 40, borderRadius: 12,
            background: `${accent}18`, color: accent,
            display:'flex', alignItems:'center', justifyContent:'center',
          }}><Icon size={20}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FONTS.display, fontSize: 24, color: theme.text, letterSpacing: -0.5, lineHeight: 1.1 }}>{goal.title}</div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute, marginTop: 4 }}>{dhText(goal.sub)}</div>
          </div>
        </div>
      </div>

      {/* Hero progress card */}
      <div style={{ padding: '0 16px 14px' }}>
        <Card theme={theme} style={{
          padding: 22,
          background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 90%)`,
        }}>
          <div style={{ display:'flex', alignItems:'center', gap: 18 }}>
            <ProgressRing
              pct={m.progressPct}
              size={104} stroke={9}
              color={accent} track={theme.surface3}
              label={`${(m.progressPct * 100).toFixed(0)}%`}
            />
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.5, textTransform: 'uppercase', color: theme.textMute }}>
                {isPayoff ? 'Remaining' : 'Saved so far'}
              </div>
              <div style={{ fontFamily: FONTS.display, fontSize: 28, color: theme.text, marginTop: 2, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>
                <Dh/> {fmtAED(m.current, {compact: m.current >= 100_000})}
              </div>
              <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textDim, marginTop: 4 }}>
                {isPayoff
                  ? <>of <Dh/> {fmtAED(goal.startingAmount, {compact: true})} starting balance</>
                  : <>of <Dh/> {fmtAED(goal.targetAmount, {compact: true})} target</>}
              </div>
              <div style={{ marginTop: 10, fontFamily: FONTS.mono, fontSize: 11.5, color: theme.text, fontVariantNumeric: 'tabular-nums' }}>
                <Dh/> {fmtAED(m.distance)} <span style={{ color: theme.textMute }}>{isPayoff ? 'left to clear' : 'to go'}</span>
              </div>
            </div>
          </div>

          {/* Trajectory */}
          <div style={{ marginTop: 18 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 6 }}>
              <SectionLabel theme={theme}>Trajectory</SectionLabel>
              <span style={{ fontFamily: FONTS.mono, fontSize: 9, letterSpacing: 1, color: theme.textMute, textTransform:'uppercase' }}>
                6m back · 6m projected
              </span>
            </div>
            <Spark data={trajectory} width={310} height={42} color={accent}/>
            <div style={{ display:'flex', justifyContent:'space-between', fontFamily: FONTS.mono, fontSize: 9, color: theme.textMute, marginTop: 4, letterSpacing: 0.5 }}>
              <span>{fmtMonthYear(addMonths(new Date(TODAY.year, TODAY.month - 1), -6))}</span>
              <span>Today</span>
              <span>{fmtMonthYear(addMonths(new Date(TODAY.year, TODAY.month - 1), 6))}</span>
            </div>
          </div>
        </Card>
      </div>

      {/* Pacing stats */}
      <div style={{ padding: '0 16px 14px' }}>
        <Card theme={theme} padded={false} style={{ display:'flex' }}>
          <PaceStat
            label="Monthly required"
            value={<><Dh/> {fmtAED(m.requiredMonthly, {compact: m.requiredMonthly >= 1000})}</>}
            sub={`to hit ${goal.targetDate}`}
            theme={theme}
          />
          <div style={{ width: 0.5, background: theme.line, margin: '12px 0' }}/>
          <PaceStat
            label="Current monthly"
            value={<><Dh/> {fmtAED(m.monthlyContribution, {compact: m.monthlyContribution >= 1000})}</>}
            sub={m.onPace ? 'on track' : 'short of pace'}
            valueColor={onPaceColor}
            theme={theme}
          />
        </Card>
      </div>

      {/* Projection card */}
      <div style={{ padding: '0 16px 14px' }}>
        <Card theme={theme} style={{ padding: 16 }}>
          <SectionLabel theme={theme}>Projected completion</SectionLabel>
          <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap: 10, marginTop: 6 }}>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, letterSpacing: -0.4 }}>
              {fmtMonthYear(projDate)}
            </div>
            <div style={{ textAlign:'right' }}>
              <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1 }}>vs target</div>
              <div style={{
                fontFamily: FONTS.mono, fontSize: 13, fontWeight: 600,
                color: projVsTarget <= 0 ? theme.positive : theme.warning,
                fontVariantNumeric: 'tabular-nums',
              }}>
                {projVsTarget === 0 ? 'on time' : projVsTarget > 0 ? `+${projVsTarget} mo late` : `${Math.abs(projVsTarget)} mo early`}
              </div>
            </div>
          </div>

          {!m.onPace && (
            <button onClick={onAskHimma} style={{
              marginTop: 12, width: '100%',
              background: `${accent}14`, color: theme.text,
              border: `0.5px solid ${accent}55`, borderRadius: 12,
              padding: '11px 14px', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 10,
              fontFamily: FONTS.ui, fontSize: 13, textAlign: 'left',
            }}>
              <div style={{ width: 24, height: 24, borderRadius: 12, background: `${accent}22`, color: accent, display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0 }}>
                <Ico.sparkles size={12}/>
              </div>
              <span style={{ flex: 1, color: theme.text }}>
                Ask Himma how to close the gap
              </span>
              <Ico.chevR size={13} stroke={theme.textDim}/>
            </button>
          )}
        </Card>
      </div>

      {/* Linked accounts */}
      {linked.length > 0 && (
        <div style={{ padding: '0 16px 14px' }}>
          <div style={{ padding: '4px 4px 8px' }}>
            <SectionLabel theme={theme}>{isPayoff ? 'Linked liability' : 'Linked accounts'}</SectionLabel>
          </div>
          <Card theme={theme} padded={false}>
            {linked.map((a, i) => (
              <div key={a.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 14px',
                borderBottom: i < linked.length - 1 ? `0.5px solid ${theme.line}` : 'none',
              }}>
                <div style={{
                  width: 34, height: 34, borderRadius: 9,
                  background: theme.surface2, border: `0.5px solid ${theme.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: FONTS.display, fontSize: 12, color: theme.text,
                  flexShrink: 0,
                }}>{a.name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, color: theme.text, fontWeight: 500 }}>{a.name}</div>
                  <div style={{ fontSize: 10.5, color: theme.textMute, fontFamily: FONTS.mono, marginTop: 2 }}>{a.sub}</div>
                </div>
                <div style={{ fontFamily: FONTS.mono, fontSize: 13, color: theme.text, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                  <Dh/> {fmtAED(a.balance, {compact: true})}
                </div>
              </div>
            ))}
          </Card>
        </div>
      )}

      {/* Footer actions */}
      <div style={{ padding: '12px 16px 0', display:'flex', gap: 8 }}>
        <button style={{
          flex: 1, background: theme.surface, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
          padding: '12px', color: theme.text, cursor: 'pointer',
          fontFamily: FONTS.ui, fontSize: 13, fontWeight: 500,
        }}>Edit goal</button>
        <button style={{
          flex: 1, background: theme.surface, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
          padding: '12px', color: theme.text, cursor: 'pointer',
          fontFamily: FONTS.ui, fontSize: 13, fontWeight: 500,
        }}>Pause</button>
        <button style={{
          width: 44, background: theme.surface, border: `0.5px solid ${theme.line2}`, borderRadius: 12,
          padding: '12px', color: theme.negative, cursor: 'pointer',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}><Ico.close size={14}/></button>
      </div>
    </Screen>
  );
}

function PaceStat({ label, value, sub, valueColor, theme }) {
  return (
    <div style={{ flex: 1, padding: '14px 16px' }}>
      <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1 }}>{label}</div>
      <div style={{ fontFamily: FONTS.display, fontSize: 18, color: valueColor || theme.text, marginTop: 4, letterSpacing: -0.3, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textDim, marginTop: 3 }}>{sub}</div>
    </div>
  );
}

// Synthetic monthly trajectory for the Spark on the detail card.
function buildGoalTrajectory(goal, m) {
  const contrib = goal.monthlyContribution || 0;
  const isDecreasing = goal.kind === 'payoff';
  const sign = isDecreasing ? -1 : 1;
  const points = [];
  // 6 historical months
  for (let i = 6; i > 0; i--) {
    points.push(Math.max(0, m.current - sign * i * contrib));
  }
  points.push(m.current); // today
  // 6 projected months
  for (let i = 1; i <= 6; i++) {
    const v = m.current + sign * i * contrib;
    if (isDecreasing && v <= 0) { points.push(0); continue; }
    if (!isDecreasing && v >= goal.targetAmount) { points.push(goal.targetAmount); continue; }
    points.push(v);
  }
  return points;
}

Object.assign(window, { GoalDetailScreen });
