// Dashboard sections — Activity ticker, My Searches, Scans grid, Privacy banner.

const { useState: useStateS, useEffect: useEffectS } = React;

// ============================================================
// Activity ticker (under the top bar)
// ============================================================
function ActivityTicker() {
  const [idx, setIdx] = useStateS(0);
  const [visible, setVisible] = useStateS(false);
  const [closed, setClosed] = useStateS(false);
  useEffectS(() => {
    if (closed) return;
    let showTimer, hideTimer;
    // Each cycle: wait (hidden), pop in for 5s with a fresh line, pop out, repeat.
    const cycle = (first) => {
      hideTimer = setTimeout(() => {
        setIdx(i => (first ? i : i + 1) % ACTIVITY_LINES.length);
        setVisible(true);
        showTimer = setTimeout(() => {
          setVisible(false);
          cycle(false);
        }, 5000);
      }, first ? 4000 : 30000);
    };
    cycle(true);
    return () => { clearTimeout(showTimer); clearTimeout(hideTimer); };
  }, [closed]);
  if (closed) return null;
  const line = ACTIVITY_LINES[idx];
  return (
    <div className={"activity-toast" + (visible ? " is-visible" : "")} aria-live="polite">
      <span className="activity-toast__dot" />
      <div className="activity-toast__body">
        <div className="activity-toast__label">Live activity</div>
        <div className="activity-toast__rail">
          <span className="activity-toast__line is-active">{line}</span>
        </div>
      </div>
      <button className="activity-toast__close" aria-label="Dismiss" onClick={() => setClosed(true)}>
        <IconX size={13} />
      </button>
    </div>
  );
}

// ============================================================
// My Searches (unified — Original Report pinned)
// ============================================================
function MySearchesSection({ rows, onView }) {
  return (
    <section>
      <div className="section__head">
        <div>
          <div className="section__title">My Searches</div>
          <div className="section__sub">Your original report and every scan you've run since</div>
        </div>
      </div>

      <div className="sw-card table-wrap">
        <table className="sw-table">
          <thead>
            <tr>
              <th>Subject</th>
              <th>Scans run</th>
              <th>Date</th>
              <th>Status</th>
              <th style={{ textAlign: "right" }}>Action</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.id} className={r.isOriginal ? "row--original" : ""}>
                <td>
                  <div className="subject">
                    <span className="sw-avatar" style={{ background: r.color, width: 36, height: 36, fontSize: 13 }}>{r.initials}</span>
                    <div>
                      <div className="subject__name">{r.name}</div>
                      <div className="subject__sub">{r.handle}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                    {r.scans.map(s => {
                      const isOriginal = s === "Original Report";
                      const accent = SCAN_NAME_ACCENT[s] || "var(--sw-blue-primary)";
                      return (
                        <span
                          key={s}
                          className={"tag" + (isOriginal ? " tag--original" : " tag--scan")}
                          style={isOriginal ? undefined : { ['--tag-accent']: accent }}
                        >
                          {isOriginal && <IconStar size={10} />}
                          {s}
                        </span>
                      );
                    })}
                  </div>
                </td>
                <td style={{ color: "var(--sw-fg-muted)", whiteSpace: "nowrap" }}>{r.date}</td>
                <td>
                  <span className="badge badge--success">
                    <span className="badge__dot" />
                    {r.status}
                  </span>
                </td>
                <td style={{ textAlign: "right" }}>
                  <button className="sw-btn sw-btn--ghost sw-btn--sm" onClick={() => onView && onView(r)}>
                    View
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ============================================================
// Scan card (with locked state + social proof + hover)
// ============================================================
function ScanCard({ scan, balance, onRun, onTopUp }) {
  const Icon = window[scan.icon] || IconScan;
  const locked = balance < scan.cost;
  const TagIcon = {
    hot: IconFlame,
    trending: IconTrend,
    popular: IconStar,
    new: IconSparkle
  }[scan.tagTone];
  return (
    <div className={"sw-card scan-card" + (locked ? " scan-card--locked" : "")}
         style={{ ['--accent']: scan.color, ['--icon-tint']: scan.color }}>
      {locked && <span className="scan-card__wash" aria-hidden />}
      <div className="scan-card__top">
        <span className="scan-card__icon" style={{ ['--icon-tint']: scan.color }}><Icon size={22} /></span>
        <div className="scan-card__main">
          {scan.tag && (
            <span className={"scan-tag scan-tag--inline scan-tag--" + scan.tagTone}>
              {TagIcon && <TagIcon size={11} />}
              {scan.tag}
            </span>
          )}
          <div className="scan-card__name">{scan.name}</div>
          <div className="scan-card__desc">{scan.desc}</div>
          <div className="scan-card__social">
            <IconUsers size={11} />
            Used {formatTokens(scan.usedThisWeek)} times this week
          </div>
        </div>
      </div>
      <div className="scan-card__bottom">
        <span className="scan-card__cost">
          <IconChip size={12} />
          {formatTokens(scan.cost)} tokens
        </span>
        {locked ? (
          <div className="scan-card__locked-cta">
            <button className="sw-btn sw-btn--sm" disabled>
              <IconLock size={13} /> Locked
            </button>
            <button className="sw-link" onClick={onTopUp}>
              Top Up to unlock <IconArrowRight size={12} />
            </button>
          </div>
        ) : (
          <button className="sw-btn sw-btn--sm scan-card__run" onClick={onRun}>
            Run Scan <IconArrowRight size={14} />
          </button>
        )}
      </div>
    </div>
  );
}

function ScansSection({ balance, onRun, onTopUp }) {
  return (
    <section>
      <div className="section__head">
        <div>
          <div className="section__title">Run a New Scan</div>
          <div className="section__sub">5 scan types · results in under 2 minutes</div>
        </div>
      </div>
      <div className="scan-grid">
        {SCAN_TYPES.map(s => (
          <ScanCard
            key={s.id}
            scan={s}
            balance={balance}
            onRun={() => onRun(s)}
            onTopUp={onTopUp}
          />
        ))}
      </div>
    </section>
  );
}

// ============================================================
// Privacy Shield banner
// ============================================================
function PrivacyBanner({ onClick }) {
  return (
    <section>
      <button className="privacy-imgbanner" onClick={onClick} aria-label="Activate Privacy Shield">
        <img src="assets/promos/privacy-banner.jpg" alt="Stop being findable. Activate Privacy Shield." draggable="false" />
      </button>
    </section>
  );
}

Object.assign(window, {
  ActivityTicker, MySearchesSection, ScansSection, ScanCard, PrivacyBanner
});
