import { getEvolutionLogs, EvolutionLog } from './history.collector';

const STORAGE_KEY = 'os:evo:pins:v1';

export interface PinnedInsight {
  id: string;
  timestamp: string;
  trend: string;
  confidence: number;
  note: string;
}

function readPins(): PinnedInsight[] {
  if (typeof window === 'undefined') return [];
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
  } catch {
    return [];
  }
}

function writePins(pins: PinnedInsight[]) {
  if (typeof window === 'undefined') return;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(pins));
}

export function getPinnedInsights(): PinnedInsight[] {
  return readPins();
}

export function pinInsight(insight: {
  timestamp: string;
  trend: string;
  confidence: number;
  note?: string;
}) {
  const pins = readPins();
  const newPin: PinnedInsight = {
    id: crypto.randomUUID(),
    timestamp: insight.timestamp,
    trend: insight.trend,
    confidence: insight.confidence,
    note: insight.note || 'Pinned insight',
  };
  pins.push(newPin);
  writePins(pins);

  // تحديث سجلّات التطور كملاحظة جديدة
  const logs = getEvolutionLogs();
  logs.push({
    id: newPin.id,
    timestamp: newPin.timestamp,
    trend: insight.trend as any,
    confidence: insight.confidence,
    changeRate: 0,
    notes: `📌 ${newPin.note}`,
  } as EvolutionLog);
  localStorage.setItem('os:evo:logs:v1', JSON.stringify(logs));

  return newPin;
}
