/* page-home.jsx — （2）Home：问候语 + 个人卡片 + Memory in use
   两张卡片结构一致：标题行（图标 + 标题 + 说明 + More ›）；中部「左内容、右大号数字」，下半部分列表占满卡片宽度；
   右列宽度一致，保证两个数字上下对齐 */
/* global React */
window.P21 = window.P21 || {};
(() => {
  const { C, SERIF, useP, Label, More, Av, Tip, Ico, D } = window.P21;
  const NUM_COL = 170; // 右侧大号数字列宽，两张卡片共用

  /* 问候语：5–12 morning，12–18 afternoon，18–次日 5 evening */
  function greetingOf(mode) {
    if (mode && mode !== 'auto') return { morning: 'Good morning', afternoon: 'Good afternoon', evening: 'Good evening' }[mode];
    const h = new Date().getHours();
    return h >= 5 && h < 12 ? 'Good morning' : h >= 12 && h < 18 ? 'Good afternoon' : 'Good evening';
  }

  /* 卡片标题行：48px 圆形图标 + 20px 粗体标题 + 灰色说明，两张卡片同一结构 */
  function Head({ icon, title, meta }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 0 }}>
        {icon}
        <span style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-.01em' }}>{title}</span>
        <span style={{ fontSize: 13, color: C.muted }}>{meta}</span>
      </div>
    );
  }

  /* 卡片：标题行（右侧 More ›，垂直居中）；中部左右分栏（左内容 / 右数字）；bottom 占满整张卡片宽度 */
  function Card({ head, left, right, bottom, more }) {
    return (
      <div style={{ marginTop: 18, background: '#fff', border: `1px solid ${C.line}`, borderRadius: 12, padding: '24px 28px 26px', boxShadow: '0 1px 3px rgba(15,15,15,.04)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
          {head}{more}
        </div>
        <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: `minmax(0,1fr) ${NUM_COL}px`, columnGap: 28 }}>
          <div>{left}</div>
          {right}
        </div>
        {bottom}
      </div>
    );
  }

  /* 右侧大号数字：浅灰底块，高度拉满上半部分；数字在上，标签和今日增量沉底 */
  function BigNum({ n, label, sub, onEnter, onLeave, children }) {
    return (
      <div onMouseEnter={onEnter} onMouseLeave={onLeave}
        style={{ position: 'relative', padding: '16px 18px 14px', borderRadius: 10, background: C.soft, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 14 }}>
        <div style={{ fontFamily: SERIF, fontSize: 46, lineHeight: 1 }}>{n}</div>
        <div>
        <div style={{ fontSize: 12, fontWeight: 600, color: C.faint }}>{label}</div>
        <div style={{ marginTop: 3, fontSize: 12.5, color: C.muted, display: 'inline-block', borderBottom: onEnter ? '1px dotted #C9C8C5' : 'none', cursor: onEnter ? 'default' : 'auto' }}>{sub}</div>
        </div>
        {children}
      </div>
    );
  }

  function ListRow({ left, right, onClick }) {
    return (
      <div onClick={onClick} className="p21-h-soft"
        style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '7px 10px', margin: '0 -10px', borderRadius: 6, cursor: onClick ? 'pointer' : 'default' }}>
        <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{left}</span>
        <span style={{ fontSize: 12, color: C.muted, whiteSpace: 'nowrap' }}>{right}</span>
      </div>
    );
  }

  function HomePage() {
    const { s, set, go, openModal } = useP();
    const [hoverReads, setHoverReads] = React.useState(false);
    const u = D.user;

    return (
      <div style={{ maxWidth: 900, margin: '0 auto', padding: '52px 48px 120px' }}>
        <div style={{ fontFamily: SERIF, fontSize: 40, lineHeight: 1.1, letterSpacing: '-.015em' }}>{greetingOf(s.greet)}, @{u.name}</div>

        {/* ── 个人卡片 ── */}
        <Card head={<Head icon={<Av size={48} uploaded={s.avatar} />} title="About you" meta={`Known since ${u.knownSince}`} />}
          left={<>
            <div style={{ fontFamily: SERIF, fontSize: 21, lineHeight: 1.42, textWrap: 'pretty' }}>{D.summary}</div>
            <div style={{ marginTop: 16, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {D.counts.map(c => (
                <span key={c.key} onClick={() => go('You', { youTab: c.key, graph: false, scrollTo: 'world' })} className="p21-h-chip"
                  style={{ padding: '3px 10px', borderRadius: 999, background: C.soft, fontSize: 12.5, color: C.muted, cursor: 'pointer' }}>
                  <b style={{ color: C.ink, fontWeight: 600 }}>{c.n}</b> {c.label}
                </span>
              ))}
              <span onClick={() => go('Playbook', { pbView: 'mine', mineTab: 'Installed', mineFilter: 'All' })} className="p21-h-chip"
                style={{ padding: '3px 10px', borderRadius: 999, background: C.soft, fontSize: 12.5, color: C.muted, cursor: 'pointer' }}>
                <b style={{ color: C.ink, fontWeight: 600 }}>{s.skills.length}</b> Skills
              </span>
            </div>
          </>}
          right={
            <BigNum n={D.memories} label="Memories" sub={`+${D.memoriesToday} today`} />
          }
          more={<More onClick={() => go('You', { graph: false })} />}
          bottom={<>
            <Label style={{ marginTop: 24, marginBottom: 4 }}>Recent memories</Label>
            {D.recentMemories.map(m => (
              <ListRow key={m.id} left={m.t} right={m.ago} onClick={() => go('Timeline', { day: 30, tlFilter: 'All', highlight: m.id })} />
            ))}
          </>}
        />

        {/* ── Memory in use ── */}
        <Card head={<Head title="Memory in use" meta={`${D.agents.filter(a => a.connected).length} of ${D.agents.length} connected`}
            icon={<span style={{ width: 48, height: 48, borderRadius: '50%', background: C.avatarBg, color: C.green, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Ico name="connections" size={22} /></span>} />}
          left={<>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {D.agents.map(a => (
                <span key={a.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '4px 11px', borderRadius: 999, border: `1px solid ${a.connected ? C.border : C.line}`, fontSize: 13, color: a.connected ? C.ink : '#AEAEB2', background: '#fff' }}>
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: a.connected ? C.greenDot : 'transparent', border: a.connected ? 'none' : '1.2px solid #C9C8C5' }} />
                  {a.name}
                </span>
              ))}
            </div>
          </>}
          right={
              <BigNum n={D.agentReads} label="Agent reads" sub={`+${D.agentReadsToday} today`}
                onEnter={() => setHoverReads(true)} onLeave={() => setHoverReads(false)}>
                {hoverReads && (
                  <Tip style={{ left: 0, top: '100%', marginTop: 8, display: 'flex', flexDirection: 'column', gap: 3, minWidth: 150 }}>
                    {D.agents.map(a => (
                      <div key={a.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 24 }}>
                        <span>{a.name}</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{a.reads}</span>
                      </div>
                    ))}
                  </Tip>
                )}
              </BigNum>
          }
          more={<More onClick={() => openModal({ type: 'connections' })} />}
          bottom={<>
            <Label style={{ marginTop: 24, marginBottom: 4 }}>Recent reads</Label>
            {D.recentReads.map((r, i) => (
              <ListRow key={i} left={<span><span style={{ fontWeight: 500 }}>{r.agent}</span> read {r.what}</span>} right={r.ago} />
            ))}
          </>}
        />
      </div>
    );
  }

  Object.assign(window.P21, { HomePage, greetingOf });
})();
