// Main tab screens: Boxes, Dashboard, Search, Loans

function BoxesScreen({ dark = false, moving = false, collapsed = false, empty = false, platform = 'ios' }) {
  const t = theme(dark, moving);
  const allBoxes = BOXES;
  // Real app: derive unique locations from boxes
  const locations = [...new Set(allBoxes.map(b => b.location))];
  const filterOptions = ['All Boxes', ...locations];
  const selectedFilter = 'All Boxes';

  // Group by location
  const grouped = locations.map(loc => ({
    location: loc,
    boxes: allBoxes.filter(b => b.location === loc),
  }));

  if (empty) {
    return (
      <Screen dark={dark} moving={moving}>
        {/* Your Boxes header — title + avatar (no download when empty) */}
        <div style={{ padding: '56px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ ...TYPE.display, color: t.textPrimary }}>Your Boxes</div>
          <Avatar dark={dark} moving={moving}/>
        </div>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <EmptyState
            dark={dark} moving={moving}
            title="No boxes yet"
            body="Add your first box or tap Scan Tag to register an NFC tag."
            illustration={<Icons.Box size={72} color={t.textTertiary} strokeWidth={1.5} />}
          />
        </div>
        <TabBar dark={dark} moving={moving} active="boxes" platform={platform} />
        <Fab dark={dark} moving={moving} platform={platform} icon={<Icons.Plus size={28} color={t.onAccent} strokeWidth={2.4} />} />
      </Screen>
    );
  }

  return (
    <Screen dark={dark} moving={moving}>
      {/* Your Boxes header: title left, Download + Avatar right */}
      {platform === 'android' ? (
        <ParallaxHeader dark={dark} moving={moving} title="Your Boxes" platform="android"
          rightAction={<div style={{ width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icons.Download size={20} color={t.accent}/></div>} />
      ) : (
        <div style={{ padding: '56px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: t.surface }}>
          <div style={{ ...TYPE.display, color: t.textPrimary }}>Your Boxes</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <div style={{ width: 44, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icons.Download size={20} color={t.accent}/>
            </div>
            <Avatar dark={dark} moving={moving}/>
          </div>
        </div>
      )}

      {/* Location filter chips (horizontal scroll) — derived from box locations */}
      <div style={{ padding: '8px 16px', display: 'flex', gap: 8, overflowX: 'auto', background: platform === 'android' ? t.bg : t.surface }}>
        {filterOptions.map(opt => (
          <FilterChip key={opt} dark={dark} moving={moving} selected={opt === selectedFilter}>
            {opt}
            {opt !== 'All Boxes' && <span style={{ opacity: 0.6, marginLeft: 4 }}>{allBoxes.filter(b => b.location === opt).length}</span>}
          </FilterChip>
        ))}
      </div>

      {/* Section list: each location has a header, then BoxCards */}
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 16px 140px' }}>
        {grouped.map(({ location, boxes }) => (
          <div key={location} style={{ marginBottom: 16 }}>
            {/* LocationSectionHeader — pill-ish, with MapPin + name + count */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 4px 6px' }}>
              <Icons.MapPin size={14} color={t.textSecondary}/>
              <div style={{ ...TYPE.overline, color: t.textSecondary, letterSpacing: 0.5 }}>{location.toUpperCase()}</div>
              <div style={{ ...TYPE.caption, color: t.textTertiary }}>· {boxes.length}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {boxes.map(b => (
                <BoxCard key={b.id} dark={dark} moving={moving}
                  name={b.name}
                  meta={`${b.location} · ${b.meta.match(/(\d+) items?/)?.[1] || '0'} items`}
                  color={b.color}
                  thumbIcon={React.createElement(Icons[b.icon], { size: 24, color: b.color })} />
              ))}
            </div>
          </div>
        ))}
      </div>

      <TabBar dark={dark} moving={moving} active="boxes" platform={platform} />
      {/* Plus FAB (Add Box) — above tab bar, bottom-right */}
      <Fab dark={dark} moving={moving} platform={platform} icon={<Icons.Plus size={28} color={t.onAccent} strokeWidth={2.4} />} />
    </Screen>
  );
}

function DashboardScreen({ dark = false, moving = false, collapsed = false, platform = 'ios' }) {
  const t = theme(dark, moving);
  return (
    <Screen dark={dark} moving={moving}>
      {/* Real app: parallax header is just BoxMind wordmark (accent color) + avatar */}
      {platform === 'android' ? (
        <ParallaxHeader dark={dark} moving={moving} title="BoxMind" collapsed={collapsed} platform="android"/>
      ) : (
        <div style={{ padding: '56px 16px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ ...TYPE.display, color: t.accent, fontWeight: 700 }}>BoxMind</div>
          <Avatar dark={dark} moving={moving}/>
        </div>
      )}
      <div style={{ flex: 1, overflow: 'auto', padding: '0 16px 140px', position: 'relative' }}>

        {/* 2×2 stats grid — in Moving Mode, adds "0/N boxes unpacked" as first card */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 12, marginBottom: 16 }}>
          {moving && <StatCard dark={dark} moving={moving} icon={<Icons.Truck size={20} />} value="0/12" label="boxes unpacked" tint={t.accent} />}
          <StatCard dark={dark} moving={moving} icon={<Icons.Package size={20} />} value="12" label="Total Boxes" tint={moving ? t.accent : undefined} />
          <StatCard dark={dark} moving={moving} icon={<Icons.Archive size={20} />} value="208" label="Total Items" tint={moving ? t.accent : undefined} />
          <StatCard dark={dark} moving={moving} icon={<Icons.Radio size={20} />} value="Never" label="Last Scanned" tint={t.amber} />
          {!moving && <StatCard dark={dark} moving={moving} icon={<Icons.HandReach size={20} />} value="5" label="Lent Out" />}
        </div>

        <div style={{ ...TYPE.h1, color: t.textPrimary, paddingTop: 8, paddingBottom: 10 }}>Quick Actions</div>

        {/* 4-across quick actions — matches real app exactly */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 8, marginBottom: 20 }}>
          <QuickActionCard dark={dark} moving={moving} icon={<Icons.Radio strokeWidth={2} />} label="Scan Box" tint={t.amber} small />
          <QuickActionCard dark={dark} moving={moving} icon={<Icons.Plus strokeWidth={2.4} />} label="Add Box" tint={t.accent} small />
          <QuickActionCard dark={dark} moving={moving} icon={<Icons.Search strokeWidth={2} />} label="Search" tint={t.accent} small />
          <QuickActionCard dark={dark} moving={moving} icon={<Icons.Sparkles strokeWidth={2} />} label="AI Coach" tint={t.aiPurple} small />
        </div>

        <div style={{ ...TYPE.h1, color: t.textPrimary, paddingTop: 8, paddingBottom: 10 }}>Recent Activity</div>
        <div style={{ background: t.surface, borderRadius: 12, boxShadow: t.shadowSm, overflow: 'hidden' }}>
          {ACTIVITY.map((a, i) => (
            <div key={i} style={{
              minHeight: 56, display: 'flex', alignItems: 'center', gap: 12, padding: '8px 16px',
              borderBottom: i === ACTIVITY.length - 1 ? 'none' : `0.5px solid ${t.sep}`,
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 18, background: `${a.color}20`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {React.createElement(Icons[a.icon], { size: 18, color: a.color })}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ ...TYPE.bodySm, color: t.textPrimary, fontWeight: 500 }}>{a.name}</div>
                <div style={{ ...TYPE.caption, color: t.textSecondary, marginTop: 1 }}>{a.meta}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* AI Coach discovery toast — pinned above tab bar */}
      <div style={{ position: 'absolute', left: 16, right: 16, bottom: platform === 'android' ? 96 : 100, background: t.surface, border: `1px solid ${t.aiPurpleLight}`, borderRadius: 12, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, boxShadow: t.shadowMd, zIndex: 5 }}>
        <div style={{ width: 32, height: 32, borderRadius: 16, background: t.aiPurpleLight, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icons.Sparkles size={16} color={t.aiPurple} />
        </div>
        <div style={{ flex: 1, ...TYPE.bodySm, color: t.textPrimary, fontWeight: 500 }}>AI Coach is available!</div>
        <div style={{ color: t.accent, fontSize: 13, fontWeight: 600 }}>Got it</div>
      </div>

      <TabBar dark={dark} moving={moving} active="dashboard" platform={platform} />
    </Screen>
  );
}

function SearchScreen({ dark = false, moving = false, state = 'results', platform = 'ios' }) {
  const t = theme(dark, moving);
  const results = [
    { name: 'Cast-iron skillet (12")',  box: 'Kitchen Essentials', loc: 'Pantry' },
    { name: 'Cast-iron lid',            box: 'Kitchen Essentials', loc: 'Pantry' },
    { name: 'Dutch oven',               box: 'Kitchen Essentials', loc: 'Pantry' },
    { name: 'Cookbook: Samin Nosrat',   box: 'Books — Fiction',    loc: 'Office shelf' },
    { name: 'Cast-iron cleaner brush',  box: 'Tools — Hand',       loc: 'Garage bin 3' },
  ];
  return (
    <Screen dark={dark} moving={moving}>
      {/* Header: Search + avatar */}
      {platform === 'android' ? (
        <ParallaxHeader dark={dark} moving={moving} title="Search" platform="android" showAvatar={false} />
      ) : (
        <div style={{ padding: '56px 16px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ ...TYPE.display, color: t.textPrimary }}>Search</div>
          <Avatar dark={dark} moving={moving} />
        </div>
      )}
      {/* SearchBar auto-focused */}
      <div style={{ padding: '8px 16px 8px' }}>
        <SearchBar dark={dark} moving={moving} value={state === 'idle' ? '' : state === 'no-results' ? 'ukelele' : 'cast'} />
      </div>

      {/* OnboardingTooltip — "Search all your boxes" */}
      {state !== 'idle' && (
        <div style={{ margin: '4px 16px 12px', background: t.aiPurpleLight, borderRadius: 12, padding: 12, display: 'flex', alignItems: 'flex-start', gap: 10 }}>
          <Icons.Sparkles size={16} color={t.aiPurple} style={{ flexShrink: 0, marginTop: 1 }}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: dark ? t.textPrimary : '#4C2889' }}>Search all your boxes</div>
            <div style={{ fontSize: 12, color: dark ? t.textSecondary : '#6B4AA3', marginTop: 2, lineHeight: 1.4 }}>Search works across all your boxes. Try searching for an item name.</div>
          </div>
          <Icons.X size={14} color={t.aiPurple}/>
        </div>
      )}

      {state === 'idle' && (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 24px', flexDirection: 'column', gap: 6 }}>
          <div style={{ ...TYPE.h1, color: t.textSecondary, textAlign: 'center' }}>Search your inventory</div>
          <div style={{ ...TYPE.body, color: t.textTertiary, textAlign: 'center' }}>Find items across all your boxes</div>
        </div>
      )}

      {state === 'no-results' && (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 24px', flexDirection: 'column', gap: 6 }}>
          <div style={{ ...TYPE.h1, color: t.textPrimary, textAlign: 'center' }}>No results</div>
          <div style={{ ...TYPE.body, color: t.textSecondary, textAlign: 'center' }}>No items match "ukelele"</div>
        </div>
      )}

      {state === 'results' && (
        <div style={{ padding: '0 16px 120px', display: 'flex', flexDirection: 'column', gap: 10, overflow: 'auto' }}>
          {results.map((r, i) => (
            <div key={i} style={{ background: t.surface, borderRadius: 12, padding: '12px 14px', boxShadow: t.shadowSm, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: t.accentLight, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icons.Package size={18} color={t.accent}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ ...TYPE.body, color: t.textPrimary, fontWeight: 500 }}>{r.name}</div>
                <div style={{ ...TYPE.label, color: t.textSecondary, marginTop: 2 }}><span style={{ color: t.accent }}>{r.box}</span> · {r.loc}</div>
              </div>
              <Icons.ChevronR size={16} color={t.textTertiary}/>
            </div>
          ))}
        </div>
      )}
      <TabBar dark={dark} moving={moving} active="search" platform={platform} />
    </Screen>
  );
}

function LoansScreen({ dark = false, moving = false, empty = false, platform = 'ios' }) {
  const t = theme(dark, moving);
  if (empty) {
    return (
      <Screen dark={dark} moving={moving}>
        {platform === 'android' ? (
          <ParallaxHeader dark={dark} moving={moving} title="Loans" platform="android" showAvatar={false} />
        ) : (
          <div style={{ padding: '56px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ ...TYPE.display, color: t.textPrimary }}>Loans</div>
            <Avatar dark={dark} moving={moving} />
          </div>
        )}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 24px', flexDirection: 'column', gap: 6 }}>
          <div style={{ ...TYPE.h1, color: t.textPrimary, textAlign: 'center' }}>Nothing lent out</div>
          <div style={{ ...TYPE.body, color: t.textSecondary, textAlign: 'center', maxWidth: 260 }}>When you lend an item, we'll track it here so nothing gets lost.</div>
        </div>
        <TabBar dark={dark} moving={moving} active="loans" platform={platform} />
      </Screen>
    );
  }
  return (
    <Screen dark={dark} moving={moving}>
      {platform === 'android' ? (
        <ParallaxHeader dark={dark} moving={moving} title="Loans" subtitle="5 active · 2 overdue" platform="android" showAvatar={false} />
      ) : (
        <div style={{ padding: '56px 16px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ ...TYPE.display, color: t.textPrimary }}>Loans</div>
            <div style={{ ...TYPE.label, color: t.textSecondary, marginTop: 2 }}>5 active · <span style={{ color: '#D97757' }}>2 overdue</span></div>
          </div>
          <Avatar dark={dark} moving={moving} />
        </div>
      )}
      <div style={{ padding: '8px 16px 12px', display: 'flex', gap: 8, overflowX: 'auto' }}>
        <FilterChip dark={dark} moving={moving} selected>All <span style={{opacity:0.7, marginLeft: 4}}>5</span></FilterChip>
        <FilterChip dark={dark} moving={moving}>Overdue <span style={{opacity:0.6, marginLeft: 4}}>2</span></FilterChip>
        <FilterChip dark={dark} moving={moving}>Due soon <span style={{opacity:0.6, marginLeft: 4}}>1</span></FilterChip>
        <FilterChip dark={dark} moving={moving}>Active</FilterChip>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: '0 16px 120px' }}>
        <div style={{ background: t.surface, borderRadius: 16, boxShadow: t.shadowSm, overflow: 'hidden' }}>
          {LOANS.map((l, i) => (
            <LoanRow key={i} dark={dark} moving={moving} {...l} last={i === LOANS.length - 1}/>
          ))}
        </div>
      </div>
      <TabBar dark={dark} moving={moving} active="loans" platform={platform} />
    </Screen>
  );
}

Object.assign(window, { BoxesScreen, DashboardScreen, SearchScreen, LoansScreen });
