/* ============================================================
   INDIC LEAGUE NEWS — Main feed (the home screen)
   Top nav + swipe card stack + bottom dock.
   Owns: sheet state, liked/saved sets, theme toggle, toast.
   ============================================================ */

function Feed({ articles, user, onLogout, theme, onToggleTheme }) {
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [sheetArticle, setSheetArticle] = React.useState(null);

  const [liked, setLiked] = React.useState(() => {
    const stored = window.IL_Util.Storage.get(window.IL_KEYS.liked, []);
    return new Set(Array.isArray(stored) ? stored : []);
  });
  const [saved, setSaved] = React.useState(() => {
    const stored = window.IL_Util.Storage.get('il_saved', []);
    return new Set(Array.isArray(stored) ? stored : []);
  });

  const [toast, setToast] = React.useState(null);
  const toastTimer = React.useRef(null);
  const showToast = (msg) => {
    if (!msg) {
      if (toastTimer.current) clearTimeout(toastTimer.current);
      setToast(null);
      return;
    }
    setToast(msg);
    if (toastTimer.current) clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 1800);
  };

  // Persist liked/saved
  React.useEffect(() => {
    window.IL_Util.Storage.set(window.IL_KEYS.liked, Array.from(liked));
  }, [liked]);
  React.useEffect(() => {
    window.IL_Util.Storage.set('il_saved', Array.from(saved));
  }, [saved]);

  const openArticle = (a) => {
    if (!a || a.is_sponsored) return;
    window.IL_Sounds && window.IL_Sounds.tap();
    window.IL_Util && window.IL_Util.Haptics.light();
    setSheetArticle(a);
    setSheetOpen(true);
  };
  const closeSheet = () => {
    setSheetOpen(false);
    // delay clearing article so transition runs
    setTimeout(() => setSheetArticle(null), 400);
  };

  const toggleLike = (a) => {
    setLiked(prev => {
      const next = new Set(prev);
      if (next.has(a.id)) {
        next.delete(a.id);
        showToast('Removed from liked');
      } else {
        next.add(a.id);
        showToast('Saved to liked ♥');
      }
      return next;
    });
  };
  const toggleSave = (a) => {
    setSaved(prev => {
      const next = new Set(prev);
      if (next.has(a.id)) {
        next.delete(a.id);
        showToast('Removed from saved');
      } else {
        next.add(a.id);
        showToast('Saved');
      }
      return next;
    });
  };
  const shareArticle = (a) => {
    showToast('Creating image…');
    window.IL_Util.shareArticle(a, (msg) => {
      if (msg) showToast(msg);
    });
  };
  const onRead = (a) => {
    // Could increment TIL score; skipped for focused scope
  };

  // Tab/dock state (for For-you vs others). Only For-you is wired.
  const [tab, setTab] = React.useState('home');

  return (
    <div className="screen" data-tab={tab}>
      {/* Top nav */}
      <header className="topnav">
        <div className="topnav-side">
          <button aria-label="Menu" onClick={() => showToast('Coming soon')}>
            <Icon name="menu" size={20} stroke={2} />
          </button>
        </div>
        <div className="brand-wordmark">
          INDIC LEAGUE<span>NEWS</span>
        </div>
        <div className="topnav-side">
          <button
            aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
            onClick={onToggleTheme}
          >
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={18} stroke={1.8} />
          </button>
          <button aria-label="Notifications" onClick={() => showToast('No new alerts')}>
            <Icon name="bell" size={18} stroke={1.8} />
          </button>
        </div>
      </header>

      {/* Main stage */}
      <div className="stage">
        {tab === 'home' && (
          <CardStack
            articles={articles}
            likedIds={liked}
            savedIds={saved}
            onOpenArticle={openArticle}
            onLike={toggleLike}
            onSave={toggleSave}
            onShare={shareArticle}
            onRead={onRead}
          />
        )}
        {tab === 'discover' && (
          <div className="empty">
            <Icon name="compass" size={36} stroke={1.6} color="var(--text-3)" />
            <h3>Discover</h3>
            <p>Topic browsing arrives in v1.1. For now, swipe the main feed — it already adapts to your topics.</p>
          </div>
        )}
        {tab === 'saved' && (
          <SavedList
            articles={articles}
            ids={liked}
            onOpen={openArticle}
            onUnlike={(a) => toggleLike(a)}
          />
        )}
        {tab === 'profile' && (
          <ProfilePanel
            user={user}
            theme={theme}
            onToggleTheme={onToggleTheme}
            onLogout={onLogout}
            liked={liked}
          />
        )}
      </div>

      {/* Bottom dock */}
      <nav className="dock" aria-label="Primary">
        <DockItem icon="home-filled" label="For you" active={tab === 'home'} onClick={() => setTab('home')} />
        <DockItem icon="compass"     label="Explore" active={tab === 'discover'} onClick={() => setTab('discover')} />
        <DockItem icon="bookmark"    label="Saved"   active={tab === 'saved'} onClick={() => setTab('saved')} />
        <DockItem icon="user"        label="Profile" active={tab === 'profile'} onClick={() => setTab('profile')} />
      </nav>

      {/* Deep dive sheet */}
      <Sheet
        open={sheetOpen}
        article={sheetArticle}
        onClose={closeSheet}
      />

      {/* Toast */}
      <div className={'toast' + (toast ? ' show' : '')}>{toast}</div>
    </div>
  );
}

function DockItem({ icon, label, active, onClick }) {
  return (
    <button
      className={'dock-item' + (active ? ' active' : '')}
      onClick={() => {
        if (active) return;
        window.IL_Sounds && window.IL_Sounds.tap();
        window.IL_Util && window.IL_Util.Haptics.light();
        onClick();
      }}
    >
      <Icon
        name={icon}
        size={22}
        stroke={1.8}
        color={active ? 'var(--coral)' : 'currentColor'}
        fill={active && icon === 'home-filled' ? 'currentColor' : 'none'}
      />
      <span>{label}</span>
    </button>
  );
}

function SavedList({ articles, ids, onOpen, onUnlike }) {
  const items = articles.filter(a => ids.has(a.id));
  if (items.length === 0) {
    return (
      <div className="empty">
        <Icon name="heart" size={42} stroke={1.4} color="var(--border-strong)" />
        <h3>Nothing liked yet</h3>
        <p>Tap the heart while reading to save stories here.</p>
      </div>
    );
  }
  return (
    <div style={{ padding: '8px 4px 24px', display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto' }}>
      {items.map(a => (
        <button
          key={a.id}
          onClick={() => onOpen(a)}
          style={{
            display: 'flex',
            background: 'var(--surface)',
            border: '1px solid var(--border)',
            borderRadius: 14,
            overflow: 'hidden',
            textAlign: 'left',
            gap: 0,
          }}
        >
          <img src={a.image} alt="" style={{ width: 94, height: 88, objectFit: 'cover', flexShrink: 0 }} />
          <div style={{ padding: '12px 14px', flex: 1, display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
            <div style={{
              fontSize: 9, fontWeight: 700, color: 'var(--coral)',
              letterSpacing: 2, textTransform: 'uppercase',
            }}>
              {a.category}
            </div>
            <div style={{
              fontFamily: 'var(--font-display)', fontWeight: 700,
              fontSize: 14, lineHeight: 1.25,
              color: 'var(--text-1)',
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
            }}>
              {a.headline}
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 'auto' }}>
              {a.publishedAt} · By {a.author}
            </div>
          </div>
          <button
            onClick={(e) => { e.stopPropagation(); onUnlike(a); }}
            aria-label="Unlike"
            style={{
              padding: '0 16px',
              color: 'var(--coral)',
              display: 'flex', alignItems: 'center',
            }}
          >
            <Icon name="heart" size={20} stroke={1.6} fill="currentColor" />
          </button>
        </button>
      ))}
    </div>
  );
}

function ProfilePanel({ user, theme, onToggleTheme, onLogout, liked }) {
  const muted = window.IL_Sounds.isMuted();
  const [muteState, setMuteState] = React.useState(muted);
  const pol = window.IL_Util.Storage.get(window.IL_KEYS.political, null);
  const topics = window.IL_Util.Storage.get(window.IL_KEYS.topics, []);

  return (
    <div style={{ padding: '8px 4px 32px', overflowY: 'auto' }}>
      {/* Profile hero */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '8px 4px 22px' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 999,
          background: 'var(--coral-soft)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontWeight: 700,
          color: 'var(--coral)', fontSize: 22,
          overflow: 'hidden',
        }}>
          {user
            ? user.name.split(' ').map(w => w[0]).join('').slice(0, 2)
            : <Icon name="user" size={28} stroke={1.6} color="var(--coral)" />}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, letterSpacing: '-0.4px', color: 'var(--text-1)' }}>
            {user ? user.name : 'Guest reader'}
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>
            {user ? user.email : 'Sign in to sync your perspective across devices'}
          </div>
        </div>
      </div>

      {/* TIL Score card */}
      <div style={{
        background: 'var(--text-1)', color: 'var(--bg)',
        borderRadius: 18, padding: '20px 22px',
        position: 'relative', overflow: 'hidden',
        marginBottom: 18,
      }}>
        <div style={{ position: 'absolute', top: -30, right: -30, width: 120, height: 120, borderRadius: 999, background: 'var(--coral)', opacity: 0.18 }} />
        <div style={{ fontSize: 10, letterSpacing: 2.4, opacity: 0.55, fontWeight: 700, textTransform: 'uppercase' }}>TIL Score</div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 44, letterSpacing: -1, marginTop: 6 }}>1,248</div>
        <div style={{ fontSize: 13, opacity: 0.7, marginTop: 4 }}>Top 12% of readers this week ↑</div>
      </div>

      {/* Perspective */}
      <SettingsSection title="Your perspective">
        <SettingsRow
          label="Political position"
          value={pol && pol.label ? pol.label : 'Not set'}
          rightHint="Edit →"
          onClick={() => {}}
        />
      </SettingsSection>

      {/* Topics */}
      <SettingsSection title="Your topics">
        <div style={{
          display: 'flex', flexWrap: 'wrap', gap: 6,
          padding: '12px 4px 4px',
        }}>
          {topics.length === 0 && <span style={{ color: 'var(--text-3)' }}>None selected</span>}
          {topics.map(id => {
            const t = window.IL_TOPICS.find(t => t.id === id);
            if (!t) return null;
            return (
              <span key={id} style={{
                padding: '6px 12px',
                borderRadius: 999,
                background: 'var(--coral-soft)',
                color: 'var(--coral)',
                fontSize: 12, fontWeight: 600,
              }}>
                {t.label}
              </span>
            );
          })}
        </div>
      </SettingsSection>

      {/* Settings */}
      <SettingsSection title="Preferences">
        <ToggleRow
          icon={theme === 'dark' ? 'moon' : 'sun'}
          label="Dark mode"
          checked={theme === 'dark'}
          onChange={onToggleTheme}
        />
        <ToggleRow
          icon={muteState ? 'volume-off' : 'volume'}
          label="Sound effects"
          checked={!muteState}
          onChange={(v) => {
            window.IL_Sounds.setMuted(!v);
            setMuteState(!v);
          }}
        />
      </SettingsSection>

      {/* Account actions */}
      {user && (
        <button
          onClick={onLogout}
          style={{
            width: '100%', padding: '14px',
            borderRadius: 14,
            border: '1px solid var(--border-strong)',
            background: 'var(--surface)',
            color: 'var(--coral)',
            fontWeight: 600,
            marginTop: 8,
          }}
        >
          Log out
        </button>
      )}
    </div>
  );
}

function SettingsSection({ title, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{
        fontSize: 10, fontWeight: 700, color: 'var(--text-3)',
        letterSpacing: 2, textTransform: 'uppercase',
        margin: '6px 4px 8px',
      }}>{title}</div>
      <div style={{
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 14,
        padding: 8,
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        {children}
      </div>
    </div>
  );
}

function SettingsRow({ label, value, rightHint, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 12px',
        borderRadius: 10,
        textAlign: 'left',
        gap: 10,
        background: 'transparent',
      }}
    >
      <span style={{ fontSize: 14, color: 'var(--text-1)', fontWeight: 500 }}>{label}</span>
      <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <span style={{ fontSize: 13, color: 'var(--text-3)' }}>{value}</span>
        {rightHint && <span style={{ fontSize: 12, color: 'var(--coral)', fontWeight: 600 }}>{rightHint}</span>}
      </span>
    </button>
  );
}

function ToggleRow({ icon, label, checked, onChange }) {
  return (
    <button
      onClick={() => {
        window.IL_Sounds && window.IL_Sounds.tap();
        window.IL_Util && window.IL_Util.Haptics.light();
        onChange(!checked);
      }}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 12px',
        borderRadius: 10,
        textAlign: 'left',
        gap: 10,
      }}
    >
      <span style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Icon name={icon} size={18} stroke={1.6} color="var(--text-2)" />
        <span style={{ fontSize: 14, color: 'var(--text-1)', fontWeight: 500 }}>{label}</span>
      </span>
      <span style={{
        width: 40, height: 24,
        borderRadius: 999,
        background: checked ? 'var(--coral)' : 'var(--border-strong)',
        position: 'relative',
        transition: 'background 180ms',
      }}>
        <span style={{
          position: 'absolute',
          top: 2, left: checked ? 18 : 2,
          width: 20, height: 20,
          borderRadius: 999,
          background: '#fff',
          transition: 'left 220ms cubic-bezier(0.175, 0.885, 0.32, 1.275)',
          boxShadow: '0 1px 3px rgba(0,0,0,0.18)',
        }} />
      </span>
    </button>
  );
}

Object.assign(window, { Feed });
