// dashboard.jsx — D-01 메인 대시보드

const { Icon, Pill, Tag, Avatar, Button, Progress, KPI } = window.RAlly;

const Dashboard = ({ go }) => {
  const [data, setData] = React.useState(null);
  React.useEffect(() => {
    fetch('/api/dashboard').then((r) => r.json()).then(setData).catch(() => {});
  }, []);
  const d = data || { kpis: [], tracks: [], team: [], dueSoon: [], recent: [] };
  const topTrack = d.topTrack || (d.tracks[0] && d.tracks[0].name) || '진행 중 트랙';
  return (
  <div className="page">
    {/* Header */}
    <div className="page__head">
      <div>
        <div className="page__title">안녕하세요{(window.RAlly.getUser && window.RAlly.getUser()) ? ', ' + window.RAlly.getUser().name + '님' : ''} <span style={{ fontSize: 24 }}>👋</span></div>
        <div className="page__sub">
          오늘은 <strong style={{ color: 'var(--coral)' }}>{topTrack}</strong>에 집중하기 좋은 날이에요.
        </div>
      </div>
      <div className="row">
        <Button variant="ghost" icon="download" onClick={() => go('share')}>내보내기</Button>
        <Button variant="primary" icon="plus" onClick={() => go('intake')}>새 트랙 만들기</Button>
      </div>
    </div>

    {/* KPI */}
    <div className="kpi-grid" style={{ marginBottom: 20 }}>
      {d.kpis.map((k, i) => (
        <KPI key={i} label={k.label} value={k.value} meta={k.meta} metaTone={k.metaTone} valueColor={k.valueColor} />
      ))}
    </div>

    {/* Body grid: 2:1 */}
    <div className="grid-2">
      {/* Left column */}
      <div className="col-v">
        {/* Track cards */}
        <div className="card card--pad">
          <div className="section-head">
            <div className="section-head__title">진행 중 트랙</div>
            <div className="section-head__action" onClick={() => go('track')}>모두 보기 →</div>
          </div>

          <div className="col-v" style={{ gap: 12 }}>
            {d.tracks.map((t, i) => (
              <DashTrackCard
                key={t.id}
                stage={t.stage}
                stageActive={i === 0}
                title={t.name}
                meta={t.meta}
                progress={t.progress}
                dDay={t.dDay}
                members={t.members}
                comments={t.comments}
                nextAction={t.nextAction}
                onClick={() => { window.__RALLY_TRACK = t.id; go('track'); }}
              />
            ))}
          </div>
        </div>

        {/* Activity feed */}
        <div className="card card--pad">
          <div className="section-head">
            <div className="section-head__title">최근 활동</div>
            <div className="section-head__action">전체 보기 →</div>
          </div>
          <div className="col-v" style={{ gap: 4 }}>
            {(d.recent || []).length === 0 && (
              <div className="muted" style={{ fontSize: 12.5, padding: '8px 2px' }}>아직 활동이 없어요. 품목 정보로 문서를 생성하면 여기에 기록됩니다.</div>
            )}
            {(d.recent || []).map((a, i) => (
              <ActivityRow key={i} avatar={{ initials: a.initials, variant: a.tone === 'coral' ? 'coral' : '' }}
                text={<><strong>{a.name}</strong>님이 <strong>{a.doc}</strong>을 {a.verb}어요</>}
                time={a.time} tone={a.tone} />
            ))}
          </div>
        </div>
      </div>

      {/* Right column */}
      <div className="col-v">
        {/* Due soon */}
        <div className="card card--pad">
          <div className="section-head">
            <div className="section-head__title">마감 임박</div>
            <Icon name="clock" size={14} style={{ color: 'var(--ink-3)' }} />
          </div>
          <div className="col-v" style={{ gap: 10 }}>
            {d.dueSoon.map((r, i) => (
              <DueRow key={i} tone={r.tone} dDay={r.dDay} title={r.title} sub={r.sub} />
            ))}
          </div>
        </div>

        {/* Team */}
        <div className="card card--pad">
          <div className="section-head">
            <div className="section-head__title">팀</div>
            <div className="section-head__action">초대 →</div>
          </div>
          <div className="col-v" style={{ gap: 10 }}>
            {d.team.map((m) => (
              <TeamRow key={m.id} initials={m.initials} variant={m.variant} name={m.name}
                role={m.role} status={m.status} muted={!!m.muted} coral={m.variant === 'coral'} />
            ))}
          </div>
        </div>

        {/* AI nudge */}
        <div className="card card--pad" style={{ background: 'var(--coral-soft)', borderColor: 'var(--coral-line)' }}>
          <div className="row" style={{ gap: 10, marginBottom: 6 }}>
            <Icon name="sparkles" size={16} style={{ color: 'var(--coral)' }} />
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--coral-2)', letterSpacing: '0.10em', textTransform: 'uppercase' }}>오늘의 RAlly 제안</div>
          </div>
          <div style={{ fontSize: 13, lineHeight: 1.55, color: '#4a2618' }}>
            품목 정보만 입력하면 적용 문서종을 실제 심사 수준으로 한 번에 생성합니다. 생성 후 증거값([입력 필요])만 채우고 RA 검토로 넘기면 됩니다.
          </div>
          <div className="row" style={{ marginTop: 10, gap: 6 }}>
            <Button variant="accent" size="sm" onClick={() => go('intake')}>문서 생성 시작 →</Button>
            <Button variant="ghost" size="sm" onClick={() => go('templates')}>템플릿 보기</Button>
          </div>
        </div>
      </div>
    </div>
  </div>
  );
};

// ---------- helpers ----------

const DashTrackCard = ({ stage, stageActive, title, meta, progress, dDay, members, comments, nextAction, onClick }) => (
  <div
    onClick={onClick}
    style={{
      border: '1px solid var(--line)',
      borderRadius: 10,
      padding: 18,
      cursor: 'pointer',
      background: 'var(--surface)',
      transition: 'border-color 180ms',
    }}
    onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--line-2)'}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--line)'}
  >
    <div className="between" style={{ marginBottom: 10 }}>
      <Pill variant={stageActive ? 'coral' : 'default'}>{stage}</Pill>
      <Icon name="dots" size={16} style={{ color: 'var(--ink-3)' }} />
    </div>
    <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em', marginBottom: 4 }}>{title}</div>
    <div className="muted" style={{ fontSize: 12.5, marginBottom: 14 }}>{meta}</div>

    <div className="between" style={{ marginBottom: 6 }}>
      <span style={{ fontSize: 11, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 700 }}>주행 거리</span>
      <span className="tabular" style={{ fontSize: 13, fontWeight: 700, color: 'var(--coral)' }}>{progress}%</span>
    </div>
    <Progress value={progress} />

    <div className="between" style={{ marginTop: 14 }}>
      <div className="row" style={{ gap: 14 }}>
        <span className="row" style={{ gap: 6, fontSize: 12, color: 'var(--ink-2)' }}>
          <Icon name="calendar" size={14} /> {dDay}
        </span>
        <div className="avatar-stack">
          {members.map((m, i) => <Avatar key={i} initials={m.initials} variant={m.variant} />)}
        </div>
        <span className="row" style={{ gap: 6, fontSize: 12, color: 'var(--ink-2)' }}>
          <Icon name="message" size={14} /> {comments}
        </span>
      </div>
      <Button variant="soft" size="sm" iconRight="arrow_right" onClick={(e) => { e.stopPropagation(); onClick(); }}>계속하기</Button>
    </div>

    <div style={{
      marginTop: 12,
      paddingTop: 12,
      borderTop: '1px dashed var(--line)',
      fontSize: 12.5,
      color: 'var(--ink-2)',
      display: 'flex', gap: 6,
    }}>
      <span style={{ color: 'var(--ink-3)', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', fontSize: 11 }}>다음 액션</span>
      <span style={{ color: 'var(--ink)', fontWeight: 500 }}>{nextAction}</span>
    </div>
  </div>
);

const ActivityRow = ({ avatar, text, time, tone }) => (
  <div className="row" style={{ padding: '10px 4px', gap: 12, borderBottom: '1px solid var(--line)' }}>
    <Avatar {...avatar} />
    <div style={{ flex: 1, fontSize: 13, lineHeight: 1.5, color: 'var(--ink-2)' }}>{text}</div>
    <span style={{ fontSize: 11.5, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{time}</span>
  </div>
);

const DueRow = ({ tone, dDay, title, sub }) => (
  <div className="row" style={{ gap: 12 }}>
    <Pill variant={tone === 'red' ? 'red' : tone === 'amber' ? 'amber' : 'default'} className="tabular">{dDay}</Pill>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{sub}</div>
    </div>
  </div>
);

const TeamRow = ({ initials, variant, name, role, status, muted, coral }) => (
  <div className="row" style={{ gap: 10 }}>
    <Avatar initials={initials} variant={variant} size="lg" />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: coral ? 'var(--coral-2)' : 'var(--ink)' }}>{name}</div>
      <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>{role}</div>
    </div>
    <div style={{ fontSize: 11.5, color: muted ? 'var(--ink-4)' : 'var(--ink-2)', textAlign: 'right' }}>{status}</div>
  </div>
);

window.RAlly.Dashboard = Dashboard;
