'use client';

import { useEffect, useState } from 'react';

const MAIN_AGENT_DRAFT_KEY = 'madarx:main-agent-draft:v1';

function readSavedDraft() {
  if (typeof window === 'undefined') return '';
  try { return window.localStorage.getItem(MAIN_AGENT_DRAFT_KEY) || ''; }
  catch { return ''; }
}

function writeSavedDraft(value) {
  if (typeof window === 'undefined') return;
  try {
    const text = String(value || '');
    if (text.trim()) window.localStorage.setItem(MAIN_AGENT_DRAFT_KEY, text);
    else window.localStorage.removeItem(MAIN_AGENT_DRAFT_KEY);
  } catch { /* storage is best-effort */ }
}

export function clearSavedDraft() {
  if (typeof window === 'undefined') return;
  try { window.localStorage.removeItem(MAIN_AGENT_DRAFT_KEY); } catch {}
}

export function useDraftPersist() {
  const [prompt, setPrompt] = useState('');

  useEffect(() => {
    const saved = readSavedDraft();
    if (saved) setPrompt(current => current || saved);
  }, []);

  useEffect(() => {
    const t = window.setTimeout(() => writeSavedDraft(prompt), 250);
    return () => window.clearTimeout(t);
  }, [prompt]);

  useEffect(() => {
    const flush = () => writeSavedDraft(prompt);
    window.addEventListener('pagehide', flush);
    document.addEventListener('visibilitychange', flush);
    return () => {
      window.removeEventListener('pagehide', flush);
      document.removeEventListener('visibilitychange', flush);
    };
  }, [prompt]);

  return { prompt, setPrompt };
}
