'use client';

import { useState } from 'react';
import styles from './ClickCategoryCard.module.css';

interface TopLink {
  href: string;
  count: number;
}

interface ClickCategoryCardProps {
  label: string;
  subLabel: string;
  value: number;
  changePercent: number;
  topLinks?: TopLink[];
}

/**
 * Format a URL for display by removing protocol and truncating if needed
 */
function formatUrl(href: string): string {
  // Remove protocol
  let formatted = href.replace(/^https?:\/\//, '');
  // Remove trailing slash
  formatted = formatted.replace(/\/$/, '');
  // Truncate if too long
  if (formatted.length > 40) {
    return formatted.substring(0, 37) + '...';
  }
  return formatted;
}

/**
 * ClickCategoryCard - Expandable card showing click stats with top links breakdown
 */
export function ClickCategoryCard({
  label,
  subLabel,
  value,
  changePercent,
  topLinks = [],
}: ClickCategoryCardProps) {
  const [expanded, setExpanded] = useState(false);

  const isPositive = changePercent >= 0;
  const hasTopLinks = topLinks.length > 0;

  return (
    <div className={styles.card}>
      <button
        className={styles.cardHeader}
        onClick={() => setExpanded(!expanded)}
        aria-expanded={expanded}
      >
        <div className={styles.headerContent}>
          <span className={styles.label}>{label}</span>
          <div className={styles.valueRow}>
            <span className={styles.value}>{value.toLocaleString()}</span>
            <span className={`${styles.change} ${isPositive ? styles.positive : styles.negative}`}>
              {isPositive ? '↑' : '↓'} {Math.abs(changePercent).toFixed(1)}%
            </span>
          </div>
          <span className={styles.subLabel}>{subLabel}</span>
        </div>
        <span className={`${styles.expandIcon} ${expanded ? styles.expanded : ''}`}>▼</span>
      </button>

      {expanded && (
        <div className={styles.breakdown}>
          <h4 className={styles.breakdownTitle}>Top Links</h4>
          {hasTopLinks ? (
            <ul className={styles.linkList}>
              {topLinks.map((link, index) => (
                <li key={index} className={styles.linkItem}>
                  <span className={styles.linkHref} title={link.href}>
                    {formatUrl(link.href)}
                  </span>
                  <span className={styles.linkCount}>{link.count}</span>
                </li>
              ))}
            </ul>
          ) : (
            <p className={styles.noData}>No link clicks recorded yet</p>
          )}
        </div>
      )}
    </div>
  );
}

export default ClickCategoryCard;
