'use client';

// Watch for a `#p=...` hash on the URL. If found, prompt the user to import
// the shared project. The project data is encoded in the URL itself (no
// server round-trip).

import { useEffect, useState } from 'react';
import { X, Link, Download } from 'lucide-react';
import { useEditor } from '@/store/editor';
import { extractShareHash, decodeShareable } from '@/lib/share/url-share';

export function ShareRestore() {
  const [pending, setPending] = useState<null | {
    name: string;
    clipCount: number;
    accept: () => Promise<void>;
    reject: () => void;
  }>(null);

  useEffect(() => {
    const hash = window.location.hash;
    const encoded = extractShareHash(hash);
    if (!encoded) return;

    (async () => {
      try {
        const proj = await decodeShareable(encoded);
        setPending({
          name: proj.name,
          clipCount: proj.clips?.length ?? 0,
          accept: async () => {
            useEditor.setState({
              projectName: proj.name,
              tracks: proj.tracks,
              clips: proj.clips,
              subtitles: proj.subtitles,
              silenceSegments: proj.silenceSegments,
              subtitleStyle: proj.subtitleStyle,
              exportSettings: proj.exportSettings,
              currentTime: 0,
              playing: false,
              history: [],
              historyIndex: -1,
            });
            useEditor.getState().setToast({
              message: `นำเข้าโปรเจกต์ "${proj.name}" แล้ว — เพิ่มไฟล์สื่อเพื่อ export`,
              level: 'success',
            });
            // Clear hash so refreshing doesn't re-prompt.
            history.replaceState(null, '', window.location.pathname);
          },
          reject: () => {
            history.replaceState(null, '', window.location.pathname);
          },
        });
      } catch (err) {
        const msg = err instanceof Error ? err.message : 'ลิงค์แชร์ไม่ถูกต้อง';
        useEditor.getState().setToast({ message: msg, level: 'error' });
      }
    })();
  }, []);

  if (!pending) return null;

  return (
    <div className="absolute top-14 left-1/2 -translate-x-1/2 z-40 bg-capcut-panel border border-capcut-blue/40 rounded-lg shadow-xl px-4 py-3 flex items-center gap-3 max-w-md">
      <Link size={20} className="text-capcut-blue shrink-0" />
      <div className="flex-1 min-w-0">
        <div className="text-sm font-medium">มีโปรเจกต์แชร์มา</div>
        <div className="text-xs text-capcut-muted truncate">
          &ldquo;{pending.name}&rdquo; · {pending.clipCount} คลิป
        </div>
      </div>
      <button
        type="button"
        onClick={() => {
          void pending.accept();
          setPending(null);
        }}
        className="px-3 py-1.5 text-sm rounded-md bg-capcut-blue hover:bg-capcut-blueDark text-white font-medium flex items-center gap-1.5"
      >
        <Download size={14} /> นำเข้า
      </button>
      <button
        type="button"
        onClick={() => {
          pending.reject();
          setPending(null);
        }}
        className="w-7 h-7 rounded text-capcut-muted hover:text-capcut-text hover:bg-capcut-border flex items-center justify-center"
        data-tip="ปฏิเสธ"
      >
        <X size={14} />
      </button>
    </div>
  );
}