// Hi-fi Assets list + Asset detail. Reads atoms from hifi-kit (window globals).

const { FONT_DISPLAY: SA_DISPLAY, FONT_BODY: SA_BODY, FONT_MONO: SA_MONO } = window.HIFI;

// ---------- Assets list — card grid ----------
const HifiAssetsScreen = ({ t, nav }) => {
  const [filter, setFilter] = React.useState('All');
  const filtered = filter === 'All' ? ASSETS : ASSETS.filter(a => a.cat === filter);
  return (
    <>
      <TopBar t={t}
        title="Assets"
        sub={`${ASSETS.length} assets across ${CATEGORIES.length} categories`}
        actions={<>
          <Btn t={t}><HIcon kind="filter" size={14}/> Sort: A→Z</Btn>
          <Btn t={t} primary onClick={() => nav.openAdd('asset')}><HIcon kind="plus" size={14}/> Add asset</Btn>
        </>}
      />
      {/* Category filter row */}
      {ASSETS.length > 0 && (
        <div style={{ display: 'flex', gap: 8, padding: '16px 28px 4px', flexWrap: 'wrap' }}>
          {['All', ...CATEGORIES].map(c => (
            <FilterChip key={c} t={t} active={filter === c} onClick={() => setFilter(c)}>{c}</FilterChip>
          ))}
        </div>
      )}
      {ASSETS.length === 0 ? (
        <EmptyState t={t} icon="grid"
          title="No assets yet"
          body="Assets are the things you maintain — your furnace, hot tub, appliances, vehicles. Add your first one, then attach its manual, specs, and a maintenance schedule."
          primaryLabel="Add your first asset" onPrimary={() => nav.openAdd('asset')}/>
      ) : (
      <div className="hh-cols-3" style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16,
        padding: '16px 28px 28px', alignContent: 'flex-start',
      }}>
        {filtered.map(a => {
          const s = assetStatusInfo(a.id);
          const accent = assetAccent(t, s);
          const tone = s.overdue ? statusTone(t,'overdue') : s.soon ? statusTone(t,'soon') : statusTone(t,'ok');
          return (
            <Card key={a.id} t={t} pad={0} onClick={() => nav.openAsset(a.id)}
              style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, padding: 18 }}>
                <div style={{
                  width: 46, height: 46, borderRadius: 12, flex: '0 0 auto',
                  background: t.inputBg, border: `1px solid ${t.border}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: t.inkSoft,
                }}><HIcon kind={CAT_ICON[a.cat] || 'grid'} size={22}/></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <Eyebrow t={t}>{a.cat || 'Uncategorized'}</Eyebrow>
                  <div style={{ fontFamily: SA_DISPLAY, fontSize: 21, fontWeight: 600, letterSpacing: -0.4, color: t.ink, marginTop: 3, lineHeight: 1.1 }}>{a.name}</div>
                  <div style={{ fontSize: 13, color: isGap(a.make) ? t.soon : t.inkSoft, marginTop: 4 }}>
                    {isGap(a.make) ? '? make & model' : (a.make !== '—' ? `${a.make} ${a.model !== '—' ? a.model : ''}`.trim() : 'No make/model yet')}
                  </div>
                </div>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: accent, marginTop: 6, flex: '0 0 auto' }}/>
              </div>
              <div style={{
                marginTop: 'auto', padding: '12px 18px',
                borderTop: `1px solid ${t.divider}`,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                {s.overdue > 0 && <Pill t={t} color={t.overdue} bg={t.overdueBg}>{s.overdue} overdue</Pill>}
                {s.soon > 0 && <Pill t={t} color={t.soon} bg={t.soonBg}>{s.soon} due soon</Pill>}
                {s.total > 0 && !s.overdue && !s.soon && <Pill t={t} color={t.ok} bg={t.okBg}>on track</Pill>}
                {s.total === 0 && <Pill t={t}>no routines</Pill>}
                <span style={{ flex: 1 }}/>
                <span style={{ fontSize: 12, color: t.inkFaint, fontFamily: SA_MONO }}>{s.total} routine{s.total !== 1 ? 's' : ''}</span>
              </div>
            </Card>
          );
        })}
      </div>
      )}
    </>
  );
};

// ---------- Asset detail ----------
const SpecRow = ({ t, k, v }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '7px 0', borderBottom: `1px solid ${t.divider}` }}>
    <span style={{ fontSize: 13, color: t.inkSoft }}>{k}</span>
    <span style={{ fontSize: 13, color: isGap(v) ? t.soon : t.ink, fontFamily: SA_MONO, fontWeight: 500 }}>{v}</span>
  </div>
);

const HifiAssetDetailScreen = ({ t, nav, assetId }) => {
  const a = findAsset(assetId);
  if (!a) return null;
  const s = assetStatusInfo(a.id);
  const accent = assetAccent(t, s);
  const rs = routinesByAsset(a.id);
  const cs = contactsByAsset(a.id);
  const ts = todosByAsset(a.id);
  const gaps = ts.filter(td => td.type === 'Info Gap');
  const tasks = ts.filter(td => td.type === 'Task');
  return (
    <>
      <TopBar t={t}
        title={a.name}
        breadcrumb={<><TLink t={t} onClick={() => nav.go('assets')}>Assets</TLink> <span style={{ color: t.inkFaint }}>/</span> {a.cat || 'Uncategorized'} <span style={{ color: t.inkFaint }}>/</span> {a.name}</>}
        sub={`${a.cat || 'Uncategorized'} · ${isGap(a.make) ? 'make & model unknown' : `${a.make} ${a.model}`.trim()}`}
        actions={<>
          <Btn t={t} onClick={() => nav.openEdit('asset', a)}>Edit</Btn>
          <Btn t={t} primary onClick={() => nav.openAdd('routine', { assetId: a.id })}><HIcon kind="plus" size={14}/> Routine</Btn>
        </>}
      />
      <div style={{ padding: '20px 28px 28px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Header card */}
        <Card t={t} pad={22} style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
          <div style={{
            width: 70, height: 70, borderRadius: 16, flex: '0 0 auto',
            background: t.inputBg, border: `1px solid ${t.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.inkSoft,
          }}><HIcon kind={CAT_ICON[a.cat] || 'grid'} size={34}/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <Eyebrow t={t}>{a.cat || 'Uncategorized'}</Eyebrow>
            <div style={{ fontFamily: SA_DISPLAY, fontSize: 34, fontWeight: 600, letterSpacing: -0.9, color: t.ink, lineHeight: 1.05, marginTop: 2 }}>{a.name}</div>
            <div style={{ fontSize: 14, color: t.inkSoft, marginTop: 6 }}>
              {isGap(a.make) ? <span style={{ color: t.soon }}>? make</span> : a.make}
              {' · '}
              {isGap(a.model) ? <span style={{ color: t.soon }}>? model</span> : a.model}
              {' · serial '}
              {a.serial && !isGap(a.serial) ? a.serial : <span style={{ color: t.soon }}>? add</span>}
              {a.year ? <>{' · '}{a.year}</> : null}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flex: '0 0 auto' }}>
            {s.overdue > 0 && <Pill t={t} color={t.overdue} bg={t.overdueBg}>{s.overdue} overdue</Pill>}
            {s.soon > 0 && <Pill t={t} color={t.soon} bg={t.soonBg}>{s.soon} due soon</Pill>}
            {s.ok > 0 && <Pill t={t} color={t.ok} bg={t.okBg}>{s.ok} on track</Pill>}
            {gaps.length > 0 && <Pill t={t}>{gaps.length} info gap{gaps.length > 1 ? 's' : ''}</Pill>}
          </div>
        </Card>

        {/* Body grid: routines | specs+notes | linked */}
        <div className="hh-split-2" style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr 1fr', gap: 16, alignItems: 'flex-start' }}>
          {/* Routines */}
          <Card t={t} pad={18}>
            <PanelHeader t={t} title={`Routines · ${rs.length}`} action={<Btn t={t} onClick={() => nav.openAdd('routine', { assetId: a.id })} style={{ padding: '5px 10px', fontSize: 12 }}><HIcon kind="plus" size={12}/> add</Btn>}/>
            {rs.length === 0 && <div style={{ color: t.inkFaint, fontSize: 13, padding: '28px 0', textAlign: 'center' }}>No routines yet.</div>}
            <div>
              {rs.map((r, i) => {
                const tone = statusTone(t, r.status);
                return (
                  <div key={r.id} onClick={() => nav.openRoutine(r.id)} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '11px 0', borderTop: i ? `1px solid ${t.divider}` : 'none', cursor: 'pointer',
                  }}>
                    <StatusDot color={tone.c} size={9}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, color: t.ink, fontWeight: 500 }}>{r.task}</div>
                      <div style={{ fontSize: 12, color: t.inkSoft, marginTop: 1 }}>{r.freq}</div>
                    </div>
                    {isUnscheduled(r)
                      ? <Btn t={t} onClick={(e) => { e.stopPropagation(); nav.openEdit('routine', r); }} style={{ padding: '4px 9px', fontSize: 11.5 }} title="Set a due date"><HIcon kind="cal" size={11}/> Schedule</Btn>
                      : <span style={{ fontSize: 13, color: tone.c, fontWeight: 500, whiteSpace: 'nowrap' }}>{r.nextLabel}</span>}
                  </div>
                );
              })}
            </div>
          </Card>

          {/* Specs + notes */}
          <Card t={t} pad={18}>
            <PanelHeader t={t} title="Specs"/>
            {Object.keys(a.specs).length === 0 && <div style={{ color: t.inkFaint, fontSize: 13 }}>No specs recorded yet.</div>}
            {Object.entries(a.specs).map(([k, v]) => <SpecRow key={k} t={t} k={k} v={v}/>)}
            <Btn t={t} onClick={() => nav.openSpec(a.id)} style={{ marginTop: 12, padding: '6px 11px', fontSize: 12 }}><HIcon kind="plus" size={12}/> add spec</Btn>
            {a.notes && <>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.ink, marginTop: 18, marginBottom: 6 }}>Notes</div>
              <div style={{ fontSize: 13, color: t.inkSoft, lineHeight: 1.5 }}>{a.notes}</div>
            </>}
          </Card>

          {/* Linked */}
          <Card t={t} pad={18}>
            <PanelHeader t={t} title="Linked" action={<Btn t={t} onClick={() => nav.openAdd('todo', { assetId: a.id })} style={{ padding: '5px 10px', fontSize: 12 }}><HIcon kind="plus" size={12}/> to-do</Btn>}/>
            <Eyebrow t={t} style={{ marginBottom: 6 }}>Contacts</Eyebrow>
            {cs.length === 0 && <div style={{ color: t.inkFaint, fontSize: 13 }}>None linked.</div>}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
              {cs.map(c => <TLink key={c.id} t={t} onClick={() => nav.openContact(c.id)} style={{ fontSize: 14 }}>{c.co}</TLink>)}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
              <Btn t={t} onClick={() => nav.openLinkContact(a.id)} style={{ padding: '5px 10px', fontSize: 12 }}><HIcon kind="link" size={12}/> link contact</Btn>
              <Btn t={t} onClick={() => nav.openAdd('contact', { assetId: a.id })} style={{ padding: '5px 10px', fontSize: 12 }}><HIcon kind="plus" size={12}/> new contact</Btn>
            </div>
            <Eyebrow t={t} style={{ marginTop: 16, marginBottom: 6 }}>To-dos · {ts.length}</Eyebrow>
            {ts.length === 0 && <div style={{ color: t.inkFaint, fontSize: 13 }}>No linked to-dos.</div>}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              {ts.map(td => {
                const done = td.status === 'Done';
                const isGapTodo = td.type === 'Info Gap';
                return (
                  <div key={td.id} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                    <span onClick={() => nav.toggleTodo(td.id)} style={{
                      width: 16, height: 16, borderRadius: 5, flex: '0 0 auto', marginTop: 1, cursor: 'pointer',
                      border: `1.5px solid ${done ? t.ok : t.border}`, background: done ? t.ok : t.inputBg,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
                    }}>{done && <HIcon kind="check" size={11}/>}</span>
                    <span style={{ flex: 1, fontSize: 13,
                      color: done ? t.inkFaint : (isGapTodo ? t.soon : t.ink),
                      textDecoration: done ? 'line-through' : 'none' }}>
                      {isGapTodo ? '? ' : ''}{td.title}
                    </span>
                    {td.priority === 'High' && !done && <Pill t={t} color={t.overdue} bg={t.overdueBg}>High</Pill>}
                  </div>
                );
              })}
            </div>
          </Card>
        </div>

        {/* Documents */}
        <DocumentsCard t={t} assetId={a.id} nav={nav}/>
      </div>
    </>
  );
};

Object.assign(window, { HifiAssetsScreen, HifiAssetDetailScreen });
