import { useState } from 'react';
import { ChevronRight, Laptop } from 'lucide-react';

interface Props {
  /** 'html' → custom <notch_html> markup (rendered as a live preview);
   *  'card' → <notch_card> preset payload (shown as formatted JSON). */
  format: 'html' | 'card';
  content: string;
  /** Preset name for 'card' format, e.g. "email" | "calendar". */
  cardType?: string;
}

/** Wrap the agent's raw notch markup in a minimal black document so the preview
 *  mirrors what showed on the Mac notch (white text on a transparent/black canvas). */
function buildSrcDoc(html: string): string {
  return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">` +
    `<style>html,body{margin:0;padding:0;background:#000;color:#fff;` +
    `font-family:-apple-system,BlinkMacSystemFont,system-ui,sans-serif;}*{box-sizing:border-box;}</style>` +
    `</head><body>${html}</body></html>`;
}

function prettyJson(raw: string): string {
  try { return JSON.stringify(JSON.parse(raw), null, 2); } catch { return raw.trim(); }
}

/**
 * Collapsible "Sent to your Mac" card. The agent emits <notch_html>/<notch_card>
 * blocks that Morphy renders in the MacBook notch — in the chat the user usually
 * doesn't want to see them, so we collapse them behind this card and let them
 * expand to preview exactly what landed on their Mac.
 */
export default function NotchCard({ format, content, cardType }: Props) {
  const [expanded, setExpanded] = useState(false);
  const label = cardType ? `Sent to your Mac · ${cardType}` : 'Sent to your Mac';

  return (
    <div className="my-2 rounded-xl border border-[#0069FE]/25 overflow-hidden">
      {/* Header */}
      <div
        onClick={() => setExpanded((v) => !v)}
        className="flex items-center gap-2.5 px-3.5 py-2.5 bg-[#0069FE]/10 hover:bg-[#0069FE]/[0.16] transition-colors cursor-pointer select-none"
      >
        <ChevronRight
          className={`h-3.5 w-3.5 text-[#4AA8FF] shrink-0 transition-transform duration-200 ${expanded ? 'rotate-90' : ''}`}
        />
        <Laptop className="h-4 w-4 text-[#4AA8FF] shrink-0" />
        <span className="text-[13px] font-medium text-[#9ecbff] truncate min-w-0">{label}</span>
      </div>

      {/* Collapsible content */}
      {expanded && (
        <div className="border-t border-[#0069FE]/15 p-3 bg-black/40">
          {format === 'html' ? (
            <iframe
              title="Mac notch card preview"
              sandbox=""
              srcDoc={buildSrcDoc(content)}
              className="w-full rounded-lg border border-white/10 bg-black block"
              style={{ height: 147 }}
            />
          ) : (
            <pre className="text-[12px] leading-relaxed text-foreground/80 overflow-x-auto whitespace-pre-wrap break-words font-mono max-h-[300px]">
              {prettyJson(content)}
            </pre>
          )}
        </div>
      )}
    </div>
  );
}
