"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import ReactFlow, {
  addEdge, Background, Controls, MiniMap,
  useEdgesState, useNodesState, ReactFlowProvider,
  Connection, Edge, Node, MarkerType, BackgroundVariant,
  Panel, getBezierPath, EdgeProps, BaseEdge, useReactFlow,
} from "reactflow";
import "reactflow/dist/style.css";
import { nanoid } from "nanoid";

import { NodeData, NodeKind, KIND_META } from "./components/nodes/nodeTypes";
import { StartNode }      from "./components/nodes/StartNode";
import { MessageNode }    from "./components/nodes/MessageNode";
import { ButtonsNode }    from "./components/nodes/ButtonsNode";
import { ConditionNode }  from "./components/nodes/ConditionNode";
import { WaitNode }       from "./components/nodes/WaitNode";
import { EndNode }        from "./components/nodes/EndNode";
import { SentimentNode }  from "./components/nodes/SentimentNode";
import { SaveVarNode }    from "./components/nodes/SaveVarNode";
import { RetryNode }      from "./components/nodes/RetryNode";
import NodePanel          from "./components/NodePanel";
import Simulator          from "./components/Simulator";
import TemplatesModal     from "./components/TemplatesModal";
import GenerateFlowModal  from "./components/GenerateFlowModal";

/* ── Node type registry ── */
const nodeTypes = {
  start: StartNode, message: MessageNode, buttons: ButtonsNode,
  condition: ConditionNode,
  wait: WaitNode, end: EndNode,
  sentiment: SentimentNode, save_var: SaveVarNode, retry: RetryNode,
};

/* ── Custom deletable edge ── */
function DeletableEdge({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, style, markerEnd, label }: EdgeProps) {
  const { setEdges } = useReactFlow();
  const [edgePath, labelX, labelY] = getBezierPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition });
  return (
    <>
      <BaseEdge id={id} path={edgePath} style={style} markerEnd={markerEnd} />
      {label && (
        <foreignObject x={labelX - 42} y={labelY - 13} width={84} height={26} style={{ overflow: "visible", pointerEvents: "none" }}>
          <div style={{ background:"#fff", border:"1.5px solid #e2e8f0", borderRadius:8, padding:"2px 6px", fontSize:10, fontWeight:700, color:"#6366f1", whiteSpace:"nowrap", textAlign:"center", boxShadow:"0 1px 4px #0001" }}>
            {label as string}
          </div>
        </foreignObject>
      )}
      <foreignObject x={labelX + (label ? 46 : -10)} y={labelY - 10} width={20} height={20} style={{ overflow:"visible" }} className="edge-delete-btn">
        <button onClick={() => setEdges(eds => eds.filter(e => e.id !== id))} title="Delete connection"
          style={{ width:20, height:20, borderRadius:"50%", background:"#ef4444", border:"2px solid #fff", color:"#fff", fontSize:11, fontWeight:900, cursor:"pointer", display:"flex", alignItems:"center", justifyContent:"center", boxShadow:"0 1px 4px #0004", lineHeight:1, padding:0 }}>
          ✕
        </button>
      </foreignObject>
    </>
  );
}
const edgeTypes = { deletable: DeletableEdge };

const EDGE = {
  type: "deletable", animated: true,
  markerEnd: { type: MarkerType.ArrowClosed, width: 18, height: 18, color: "#6366f1" },
  style: { strokeWidth: 2.5, stroke: "#6366f1" },
};

/* ── Starter flow ── */
const INIT_NODES: Node<NodeData>[] = [
  { id:"s1",  type:"start",    position:{x:60,y:200},  data:{kind:"start",    label:"New Booking",        content:"booking_created"} },
  { id:"m1",  type:"message",  position:{x:360,y:200}, data:{kind:"message",  label:"Welcome Message",    content:"Hi {{name}}! 🎉 Your *{{treatment}}* is confirmed!\n\n📅 *Date:* {{date}}\n🕐 *Time:* {{time}}\n🏥 {{clinic}}\n\nWe can't wait to see you! 💙"} },
  { id:"b1",  type:"buttons",  position:{x:720,y:200}, data:{kind:"buttons",  label:"Confirm or Reschedule", content:"Can you confirm your attendance, {{name}}?", buttons:[{id:"yes",label:"✅ Yes, I'll be there",text:"✅ Yes, I'll be there"},{id:"reschedule",label:"📅 Reschedule",text:"📅 Reschedule"},{id:"cancel",label:"❌ Cancel",text:"❌ Cancel"}]} },
  { id:"m2",  type:"message",  position:{x:1080,y:60}, data:{kind:"message",  label:"Confirmed! 🎉",       content:"Wonderful! ✅ You're all set, {{name}}!\n\nArrive *10 minutes early* and bring your ID.\n\nSee you on {{date}} at {{time}}! 🙏"} },
  { id:"m3",  type:"message",  position:{x:1080,y:260},data:{kind:"message",  label:"Reschedule Handler",  content:"No problem at all, {{name}}! 😊 Please share 2-3 preferred dates and times and we'll get you rebooked right away."} },
  { id:"e1",  type:"end",      position:{x:1420,y:60}, data:{kind:"end",      label:"Journey Complete"} },
];
const INIT_EDGES: Edge[] = [
  {id:"e1",source:"s1",target:"m1",...EDGE},
  {id:"e2",source:"m1",target:"b1",...EDGE},
  {id:"e3",source:"b1",sourceHandle:"yes",target:"m2",label:"✅ Confirm",...EDGE,style:{strokeWidth:2.5,stroke:"#059669"},markerEnd:{type:MarkerType.ArrowClosed,width:18,height:18,color:"#059669"}},
  {id:"e4",source:"b1",sourceHandle:"reschedule",target:"m3",label:"📅 Reschedule",...EDGE,style:{strokeWidth:2.5,stroke:"#d97706"},markerEnd:{type:MarkerType.ArrowClosed,width:18,height:18,color:"#d97706"}},
  {id:"e5",source:"m2",target:"e1",...EDGE},
];

const PALETTE: NodeKind[] = ["message","buttons","condition","sentiment","save_var","retry","wait","end"];

export default function ChatbotCanvasPage() {
  return <ReactFlowProvider><Canvas /></ReactFlowProvider>;
}

/* ════════════ VALIDATOR TYPES ════════════ */
interface ValidationResult {
  issues: { nodeId?: string; nodeLabel?: string; severity: "error"|"warning"|"tip"; message: string; fix: string }[];
  score: number;
  ready: boolean;
  summary: { errors: number; warnings: number; tips: number };
}

/* ════════════ CANVAS ════════════ */
function Canvas() {
  const [nodes, setNodes, onNodesChange] = useNodesState<NodeData>(INIT_NODES);
  const [edges, setEdges, onEdgesChange] = useEdgesState(INIT_EDGES);
  const [selectedId, setSelectedId]   = useState<string | null>(null);
  const [treeName, setTreeName]        = useState("Appointment Reminder Flow");
  const [treeId, setTreeId]           = useState<string | null>(null);
  const [saving, setSaving]           = useState(false);
  const [deploying, setDeploying]     = useState(false);
  const [dirty, setDirty]            = useState(false);
  const [savedOk, setSavedOk]        = useState(false);
  const [generating, setGenerating]  = useState(false);
  const [translating, setTranslating]= useState(false);
  const [toast, setToast]            = useState<{msg:string;ok:boolean}|null>(null);
  const [rfInstance, setRfInstance]  = useState<any>(null);
  const wrapperRef    = useRef<HTMLDivElement>(null);
  // Modals
  const [showSimulator, setShowSimulator]   = useState(false);
  const [showTemplates, setShowTemplates]   = useState(false);
  const [showGenerator, setShowGenerator]   = useState(false);
  const [generatorTemplateType, setGeneratorTemplateType] = useState<string | undefined>(undefined);
  const [clinicType, setClinicType]         = useState("Medical Clinic");
  const [showHelp, setShowHelp]             = useState(false);
  const [showTranslateMenu, setShowTranslateMenu] = useState(false);
  const translateBtnRef = useRef<HTMLButtonElement>(null);
  // Validator
  const [validation, setValidation]   = useState<ValidationResult | null>(null);
  const [validating, setValidating]   = useState(false);
  const [showValidator, setShowValidator] = useState(false);
  // Live Info Panel
  const [showLiveInfo, setShowLiveInfo] = useState(false);
  const [liveInfo, setLiveInfo] = useState<{ treeName: string; triggerType: string; nodeCount: number; edgeCount: number; deployedAt: string } | null>(null);
  // Analytics overlay — real data from API
  const [showAnalytics, setShowAnalytics]   = useState(false);
  const [analyticsLoading, setAnalyticsLoading] = useState(false);
  const [realStats, setRealStats] = useState<{
    summary: any;
    nodeStats: Record<string, {executed:number;failed:number;skipped:number}>;
    baselineSent: number;
    baselineResp: number;
  } | null>(null);
  // Version history (last 5 snapshots)
  const [history, setHistory]         = useState<{name:string;nodes:any[];edges:any[];at:string}[]>([]);
  const [showHistory, setShowHistory] = useState(false);

  const selected = nodes.find(n => n.id === selectedId) ?? null;
  const mark   = useCallback(() => { setDirty(true); setSavedOk(false); }, []);
  const unmark = useCallback(() => { setDirty(false); setSavedOk(true); }, []);
  const toast$ = useCallback((msg:string, ok=true) => {
    setToast({msg, ok});
    setTimeout(() => setToast(null), 3500);
  }, []);

  const onConnect = useCallback((c: Connection) => { setEdges(eds => addEdge({...c,...EDGE}, eds)); mark(); }, [setEdges, mark]);
  const onNodeClick = useCallback((_:any, node:Node) => setSelectedId(node.id), []);
  const onPaneClick = useCallback(() => setSelectedId(null), []);
  const [selectedEdgeId, setSelectedEdgeId] = useState<string|null>(null);
  const onEdgeClick = useCallback((_:any, edge:Edge) => { setSelectedEdgeId(edge.id); setSelectedId(null); }, []);

  /* ── Load clinic type from profile ── */
  useEffect(() => {
    fetch("/api/clinic")
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d?.clinicType) setClinicType(d.clinicType); })
      .catch(() => {});
  }, []);

  /* ── Add node ── */
  const addNode = useCallback((kind: NodeKind) => {
    const id = `${kind}-${nanoid(4)}`;
    const defs: Record<string,Partial<NodeData>> = {
      message:     {label:"New Message",   content:""},
      buttons:     {label:"Give Choices",  content:"", buttons:[]},
      condition:   {label:"Smart Branch",  branches:[]},
      sentiment:   {label:"Mood Router"},
      save_var:    {label:"Remember Answer", varName:"answer", varPrompt:""},
      retry:       {label:"Smart Retry",   retryDelayMinutes:1440, maxRetries:2, retryMessage:""},
      wait:        {label:"Wait 1 hour",   delayMinutes:60},
      end:         {label:"Journey End"},
    };
    const d = defs[kind] ?? {};
    const vp = rfInstance?.getViewport?.() ?? {x:0,y:0,zoom:1};
    const cx = (-vp.x + (wrapperRef.current?.clientWidth  ?? 700)/2) / vp.zoom;
    const cy = (-vp.y + (wrapperRef.current?.clientHeight ?? 500)/2) / vp.zoom;
    setNodes(nds => [...nds, { id, type:kind, position:{x:cx-120+Math.random()*60, y:cy-60+Math.random()*60}, data:{kind, label:d.label??kind, ...d} as NodeData }]);
    setSelectedId(id);
    mark();
  }, [rfInstance, setNodes, mark]);

  const onDataChange = useCallback((id:string, patch:Partial<NodeData>) => {
    setNodes(nds => nds.map(n => n.id===id ? {...n,data:{...n.data,...patch}} : n));
    mark();
  }, [setNodes, mark]);

  const onDelete = useCallback((id:string) => {
    setNodes(nds => nds.filter(n => n.id!==id));
    setEdges(eds => eds.filter(e => e.source!==id && e.target!==id));
    if (selectedId===id) setSelectedId(null);
    mark();
  }, [setNodes, setEdges, selectedId, mark]);

  /* ── AI Generate content ── */
  const onAIGenerate = useCallback(async (nodeId:string, field:string) => {
    const node = nodes.find(n => n.id===nodeId);
    if (!node) return;
    setGenerating(true);
    setNodes(nds => nds.map(n => n.id===nodeId ? {...n,data:{...n.data,generating:true}} : n));
    try {
      const res = await fetch("/api/chatbot-canvas/ai-generate", {
        method:"POST", headers:{"Content-Type":"application/json"},
        body: JSON.stringify({nodeKind:node.data.kind, nodeLabel:node.data.label, field, currentContent:(node.data as any)[field]||"", treeName}),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error||"AI error");
      setNodes(nds => nds.map(n => n.id===nodeId ? {...n,data:{...n.data,[field]:json.result,generating:false}} : n));
      mark();
      toast$("✨ Content generated by Claude!");
    } catch(e:any) {
      toast$("❌ "+e.message, false);
      setNodes(nds => nds.map(n => n.id===nodeId ? {...n,data:{...n.data,generating:false}} : n));
    } finally { setGenerating(false); }
  }, [nodes, setNodes, treeName, mark, toast$]);

  /* ── Save ── */
  const onSave = useCallback(async () => {
    if (saving) return;
    // Push to version history
    setHistory(h => [{name:treeName, nodes, edges, at: new Date().toLocaleTimeString()}, ...h].slice(0,5));
    setSaving(true);
    try {
      const res = await fetch("/api/chatbot-canvas/save", {
        method:"POST", headers:{"Content-Type":"application/json"},
        body: JSON.stringify({treeId, treeName, nodes, edges}),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error);
      setTreeId(json.treeId);
      unmark();
      toast$("💾 Flow saved!");
    } catch(e:any) { toast$("❌ Save failed: "+e.message, false); } finally { setSaving(false); }
  }, [saving, treeId, treeName, nodes, edges, unmark, toast$]);

  /* ── Validate + Deploy ── */
  const onValidateAndDeploy = useCallback(async () => {
    if (!treeId) { toast$("Save the flow first", false); return; }
    if (dirty)   { toast$("You have unsaved changes — save first", false); return; }
    setValidating(true);
    setShowValidator(true);
    try {
      const res = await fetch("/api/chatbot-canvas/validate", {
        method:"POST", headers:{"Content-Type":"application/json"},
        body: JSON.stringify({nodes, edges}),
      });
      const json = await res.json();
      setValidation(json);
      if (json.ready) {
        // Auto-deploy if no errors
        setValidating(false);
        setDeploying(true);
        const depRes = await fetch("/api/chatbot-canvas/deploy", {
          method:"POST", headers:{"Content-Type":"application/json"},
          body: JSON.stringify({treeId}),
        });
        const depJson = await depRes.json();
        if (!depRes.ok) throw new Error(depJson.error);
        toast$("🚀 Flow is now LIVE on WhatsApp!");
        setShowValidator(false);
        // Show live info in right panel
        const startNode = nodes.find(n => n.data?.kind === "start");
        setLiveInfo({
          treeName,
          triggerType: startNode?.data?.content ?? "booking_created",
          nodeCount: nodes.length,
          edgeCount: edges.length,
          deployedAt: new Date().toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }),
        });
        setShowLiveInfo(true);
      }
    } catch(e:any) { toast$("❌ "+e.message, false); }
    finally { setValidating(false); setDeploying(false); }
  }, [treeId, dirty, nodes, edges, toast$]);

  /* ── Translate ── */
  const onTranslate = useCallback(async (lang: string) => {
    setTranslating(true);
    toast$(`🌍 Translating to ${lang}…`);
    try {
      const res = await fetch("/api/chatbot-canvas/translate", {
        method:"POST", headers:{"Content-Type":"application/json"},
        body: JSON.stringify({nodes, targetLanguage: lang}),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error);
      setNodes(json.nodes);
      mark();
      toast$(`✅ Translated ${json.translatedCount} blocks to ${lang}!`);
    } catch(e:any) { toast$("❌ "+e.message, false); }
    finally { setTranslating(false); }
  }, [nodes, setNodes, mark, toast$]);

  /* ── Load flow (from template or AI generator) ── */
  const loadFlow = useCallback((newNodes: any[], newEdges: any[], name: string) => {
    setNodes(newNodes);
    setEdges(newEdges);
    setTreeName(name);
    setTreeId(null);
    setSelectedId(null);
    mark();
    setShowTemplates(false);
    setShowGenerator(false);
    toast$(`✅ "${name}" loaded — ${newNodes.length} blocks ready!`);
    setTimeout(() => rfInstance?.fitView({padding:0.2}), 100);
  }, [setNodes, setEdges, mark, toast$, rfInstance]);

  /* ── Keyboard shortcuts ── */
  useEffect(() => {
    const h = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement).tagName;
      if (tag==="INPUT"||tag==="TEXTAREA"||tag==="SELECT") return;
      if ((e.key==="Delete"||e.key==="Backspace") && selectedId) onDelete(selectedId);
      if ((e.metaKey||e.ctrlKey) && e.key==="s") { e.preventDefault(); onSave(); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [selectedId, onDelete, onSave]);

  /* ── Fetch real analytics when overlay is toggled on ── */
  useEffect(() => {
    if (!showAnalytics) return;
    setAnalyticsLoading(true);
    fetch("/api/chatbot-canvas/stats")
      .then(r => r.json())
      .then(data => setRealStats(data))
      .catch(() => setRealStats(null))
      .finally(() => setAnalyticsLoading(false));
  }, [showAnalytics]);

  /* ── Build stable per-node analytics (memoised — no Math.random in render) ── */
  const analyticsData = useMemo<Record<string, {sent:number;responded:number;dropped:number}>>(() => {
    if (!showAnalytics) return {};
    const out: Record<string, {sent:number;responded:number;dropped:number}> = {};
    const baseline  = realStats?.baselineSent ?? 0;
    const respBase  = realStats?.baselineResp ?? 0;
    const nodeStats = realStats?.nodeStats ?? {};
    nodes.forEach((n, i) => {
      const nStat = nodeStats[n.id];
      if (nStat && (nStat.executed + nStat.failed + nStat.skipped) > 0) {
        // Real NodeExecution data
        const total = nStat.executed + nStat.failed + nStat.skipped;
        out[n.id] = { sent: total, responded: nStat.executed, dropped: nStat.skipped + nStat.failed };
      } else if (baseline > 0) {
        // Project from appointment data — drop-off increases with depth
        const dropFactor = Math.max(0, 1 - i * 0.08);
        const sent       = Math.round(baseline * dropFactor);
        const responded  = Math.round(respBase  * dropFactor);
        out[n.id] = { sent: Math.max(sent, 0), responded: Math.max(responded, 0), dropped: Math.max(sent - responded, 0) };
      }
    });
    return out;
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showAnalytics, realStats, nodes.length]);

  return (
    <div className="flex h-full overflow-hidden bg-gray-50">

      {/* ══════════ LEFT PANEL ══════════ */}
      <div className="w-[210px] flex-shrink-0 bg-white border-r border-gray-200 flex flex-col overflow-hidden panel-left-enter">
        {/* Logo */}
        <div className="px-4 py-3 border-b border-gray-100 bg-gradient-to-r from-indigo-600 to-violet-600">
          <div className="flex items-center gap-2">
            <span className="text-lg">🌳</span>
            <span className="text-[13px] font-bold text-white">Chatbot Canvas</span>
          </div>
          <p className="text-[10px] text-white/60 mt-0.5">Build your WhatsApp flow</p>
        </div>

        {/* Flow name */}
        <div className="px-3 py-2.5 border-b border-gray-100">
          <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Flow Name</p>
          <input className="w-full text-[12px] font-semibold text-gray-700 bg-gray-50 rounded-lg px-2.5 py-1.5 border border-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-400"
            value={treeName} onChange={e => { setTreeName(e.target.value); mark(); }} placeholder="Flow name…" />
        </div>

        {/* AI Feature buttons */}
        <div className="px-3 py-2.5 border-b border-gray-100 space-y-1.5">
          <button onClick={() => setShowTemplates(true)}
            className="w-full flex items-center gap-2.5 px-3 py-2.5 rounded-xl bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white text-[12px] font-bold hover:opacity-90 transition shadow-md">
            <span className="text-base">📋</span>
            <span className="flex-1 text-left">Templates & AI Generator</span>
            <span className="text-white/60 text-[10px]">→</span>
          </button>
          <button onClick={() => setShowSimulator(true)}
            className="w-full flex items-center gap-2 px-3 py-2 rounded-xl bg-green-50 text-green-700 border border-green-100 text-[11px] font-bold hover:bg-green-100 transition">
            <span>📱</span> Preview on Phone
          </button>
          {/* Translate */}
          <button ref={translateBtnRef}
            disabled={translating}
            onClick={() => setShowTranslateMenu(v => !v)}
            className="w-full flex items-center gap-2 px-3 py-2 rounded-xl bg-cyan-50 text-cyan-700 border border-cyan-100 text-[11px] font-bold hover:bg-cyan-100 transition disabled:opacity-60">
            <span>{translating ? "⏳" : "🌍"}</span>
            <span className="flex-1 text-left">{translating ? "Translating…" : "Translate Flow"}</span>
            <span className="text-[9px] opacity-50">{showTranslateMenu ? "▲" : "▼"}</span>
          </button>
        </div>

        {/* Node palette */}
        <div className="flex-1 overflow-y-auto px-3 py-2.5">
          <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Add Blocks</p>
          <div className="space-y-1">
            {PALETTE.map(kind => {
              const m = KIND_META[kind];
              return (
                <button key={kind} onClick={() => addNode(kind)}
                  className="palette-btn w-full flex items-center gap-2 px-2.5 py-2 rounded-xl border text-left"
                  style={{ background:m.light, color:m.color, borderColor:m.border }}>
                  <span className="text-base leading-none flex-shrink-0">{m.icon}</span>
                  <div className="min-w-0">
                    <p className="text-[11px] font-bold truncate leading-tight">{m.label}</p>
                    <p className="text-[9px] opacity-60 truncate leading-tight">{m.description}</p>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Actions */}
        <div className="px-3 py-3 border-t border-gray-100 space-y-1.5">
          {/* Save */}
          <button onClick={onSave} disabled={saving||!dirty}
            className={`w-full flex items-center justify-center gap-1.5 py-2 rounded-xl text-[12px] font-bold transition ${dirty&&!saving?"bg-indigo-600 text-white hover:bg-indigo-700 shadow-sm":"bg-gray-100 text-gray-400 cursor-not-allowed"}`}>
            {saving ? <><span className="w-3 h-3 rounded-full border-2 border-white border-t-transparent animate-spin"/>Saving…</> : <><span>💾</span>{dirty?"Save Changes":"Saved ✓"}</>}
          </button>
          {/* Validate + Deploy */}
          <button onClick={onValidateAndDeploy} disabled={deploying||dirty||!treeId}
            title={dirty?"Save first":!treeId?"Save first":"Validate & deploy to WhatsApp"}
            className={`w-full flex items-center justify-center gap-1.5 py-2 rounded-xl text-[12px] font-bold transition ${!dirty&&treeId&&!deploying?"bg-emerald-600 text-white hover:bg-emerald-700 shadow-sm":"bg-gray-100 text-gray-400 cursor-not-allowed"}`}>
            {deploying||validating ? <><span className="w-3 h-3 rounded-full border-2 border-white border-t-transparent animate-spin"/>{validating?"Checking…":"Deploying…"}</> : <><span>🚀</span>Validate & Go Live</>}
          </button>
          {/* Extras row */}
          <div className="flex gap-1.5">
            <button onClick={() => { setShowAnalytics(a => !a); if (!showAnalytics) setRealStats(null); }} title="Analytics overlay"
              className={`flex-1 py-1.5 rounded-lg text-[10px] font-bold border transition flex items-center justify-center gap-1 ${showAnalytics?"bg-orange-500 text-white border-orange-500":"border-gray-200 text-gray-500 hover:bg-gray-50"}`}>
              {analyticsLoading ? <span className="w-2.5 h-2.5 rounded-full border-2 border-current border-t-transparent animate-spin"/> : "📊"} Stats
            </button>
            <button onClick={() => setShowHistory(h => !h)} title="Version history"
              className={`flex-1 py-1.5 rounded-lg text-[10px] font-bold border transition ${showHistory?"bg-slate-700 text-white border-slate-700":"border-gray-200 text-gray-500 hover:bg-gray-50"}`}>
              🕐 History
            </button>
            <button onClick={() => setShowHelp(true)} className="flex-1 py-1.5 rounded-lg text-[10px] font-bold border border-gray-200 text-gray-500 hover:bg-gray-50 transition">
              ❓ Help
            </button>
          </div>
        </div>
      </div>

      {/* ══════════ CANVAS ══════════ */}
      <div ref={wrapperRef} className="flex-1 h-full relative canvas-ready">
        <ReactFlow
          nodes={nodes.map(n => showAnalytics && analyticsData[n.id]
            ? {...n, data:{...n.data, analytics: analyticsData[n.id]}}
            : n
          )}
          edges={edges}
          onNodesChange={ch => { onNodesChange(ch); mark(); }}
          onEdgesChange={ch => { onEdgesChange(ch); mark(); }}
          onConnect={onConnect}
          onNodeClick={onNodeClick}
          onEdgeClick={onEdgeClick}
          onPaneClick={() => { onPaneClick(); setSelectedEdgeId(null); }}
          onInit={setRfInstance}
          nodeTypes={nodeTypes}
          edgeTypes={edgeTypes}
          defaultEdgeOptions={EDGE}
          fitView fitViewOptions={{padding:0.2}}
          snapToGrid snapGrid={[20,20]}
          deleteKeyCode={null}
          minZoom={0.2} maxZoom={2}
          edgesUpdatable edgesFocusable
        >
          <Background variant={BackgroundVariant.Dots} gap={24} size={1.2} color="#dde1ec" />
          <Controls showInteractive={false} style={{bottom:16,right:16,top:"auto",left:"auto",flexDirection:"column"}} />
          <MiniMap
            nodeColor={n => KIND_META[(n.data as NodeData)?.kind as NodeKind]?.color ?? "#888"}
            style={{bottom:130,right:16,top:"auto",left:"auto",borderRadius:12,border:"1.5px solid #e2e8f0"}}
            pannable zoomable
          />

          {/* Status badge */}
          <Panel position="top-right" style={{margin:12}}>
            <div className="flex items-center gap-2 bg-white/95 backdrop-blur border border-gray-200 rounded-xl px-3 py-2 shadow-sm text-[11px] font-semibold">
              {dirty ? <><span className="w-2 h-2 rounded-full bg-amber-400 status-dot-live"/><span className="text-amber-600">Unsaved</span></>
                : savedOk ? <><span className="w-2 h-2 rounded-full bg-emerald-400 status-dot-live"/><span className="text-emerald-600">Saved</span></>
                : <><span className="w-2 h-2 rounded-full bg-gray-300"/><span className="text-gray-400">Draft</span></>}
              <span className="text-gray-200">|</span>
              <span className="text-gray-400">{nodes.length} blocks · {edges.length} connections</span>
              <span className="text-gray-200">|</span>
              <span className="text-gray-400">⌘S</span>
            </div>
          </Panel>

          {/* Analytics legend + real summary */}
          {showAnalytics && (
            <Panel position="bottom-left" style={{margin:12}}>
              <div className="bg-white/95 border border-gray-200 rounded-2xl px-4 py-3 shadow-lg text-[11px]" style={{minWidth:220}}>
                <div className="flex items-center gap-2 mb-2">
                  <span className="font-bold text-gray-700">📊 Analytics Overlay</span>
                  {analyticsLoading && <span className="w-3 h-3 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin ml-auto"/>}
                </div>
                {realStats?.summary && (
                  <div className="grid grid-cols-2 gap-1.5 mb-2">
                    {[
                      { label:"Appointments", value: realStats.summary.totalAppts,   color:"#6366f1" },
                      { label:"Confirmed",    value: `${realStats.summary.confirmRate}%`, color:"#059669" },
                      { label:"No-Shows",     value: realStats.summary.noShows,      color:"#dc2626" },
                      { label:"Data source",  value: realStats.summary.hasRealData ? "Real journeys" : "Appointments", color:"#6b7280" },
                    ].map(s => (
                      <div key={s.label} className="bg-gray-50 rounded-lg px-2 py-1.5 border border-gray-100">
                        <p className="text-[9px] text-gray-400 font-semibold">{s.label}</p>
                        <p className="text-[12px] font-black" style={{color:s.color}}>{s.value}</p>
                      </div>
                    ))}
                  </div>
                )}
                <div className="flex items-center gap-3 text-[10px] font-semibold border-t border-gray-100 pt-2">
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-emerald-400"/>Sent</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-blue-400"/>Replied</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-red-400"/>Dropped</span>
                </div>
                {!realStats?.summary?.hasRealData && !analyticsLoading && (
                  <p className="text-[9px] text-gray-400 mt-1.5 leading-tight">
                    ⚠️ Estimated from appointment data.<br/>Deploy flows to collect real node stats.
                  </p>
                )}
              </div>
            </Panel>
          )}

          {nodes.length === 0 && (
            <Panel position="top-center" style={{marginTop:"25%"}}>
              <div className="text-center pointer-events-none select-none opacity-50">
                <div className="text-6xl mb-3">🌳</div>
                <p className="text-[14px] font-bold text-gray-400">Click a block on the left, or try "Generate with AI"</p>
              </div>
            </Panel>
          )}
        </ReactFlow>


      </div>

      {/* ══════════ RIGHT PANEL ══════════ */}
      <div className="flex-shrink-0 h-full overflow-hidden panel-right-enter" style={{width:showValidator||showHistory||showLiveInfo?320:300}}>
        {showLiveInfo && liveInfo ? (
          <LiveInfoPanel
            info={liveInfo}
            onClose={() => setShowLiveInfo(false)}
          />
        ) : showValidator && validation ? (
          <ValidatorPanel
            validation={validation}
            onClose={() => setShowValidator(false)}
            onHighlight={id => { setSelectedId(id); setShowValidator(false); }}
          />
        ) : showHistory ? (
          <HistoryPanel
            history={history}
            onRestore={snap => { setNodes(snap.nodes); setEdges(snap.edges); setTreeName(snap.name); mark(); setShowHistory(false); toast$("🕐 Restored version from "+snap.at); }}
            onClose={() => setShowHistory(false)}
          />
        ) : (
          <NodePanel
            key={selectedId ?? "__empty__"}
            node={selected}
            onChange={onDataChange}
            onDelete={onDelete}
            onAIGenerate={onAIGenerate}
            generating={generating}
          />
        )}
      </div>

      {/* ══ Toast ══ */}
      {toast && (
        <div className={`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 px-5 py-3 rounded-2xl text-[13px] font-bold shadow-2xl text-white toast-enter ${toast.ok?"bg-gray-900":"bg-red-600"}`}>
          {toast.msg}
        </div>
      )}

      {/* ══ Translate dropdown (fixed to escape overflow) ══ */}
      {showTranslateMenu && !translating && (() => {
        const rect = translateBtnRef.current?.getBoundingClientRect();
        return (
          <>
            <div className="fixed inset-0 z-40" onClick={() => setShowTranslateMenu(false)} />
            <div className="fixed z-50 bg-white border border-gray-200 rounded-2xl shadow-2xl overflow-hidden modal-enter"
              style={{ top: rect ? rect.bottom + 6 : 200, left: rect ? rect.left : 12, width: 160 }}>
              <p className="px-3 pt-2.5 pb-1.5 text-[10px] font-bold text-gray-400 uppercase tracking-wider">Translate to</p>
              {[
                { lang:"Arabic",  flag:"🇸🇦" },
                { lang:"French",  flag:"🇫🇷" },
                { lang:"Spanish", flag:"🇪🇸" },
                { lang:"Turkish", flag:"🇹🇷" },
                { lang:"German",  flag:"🇩🇪" },
              ].map(({ lang, flag }) => (
                <button key={lang}
                  onClick={() => { setShowTranslateMenu(false); onTranslate(lang); }}
                  className="w-full flex items-center gap-2.5 px-3 py-2.5 text-[12px] font-semibold text-gray-700 hover:bg-cyan-50 hover:text-cyan-700 transition text-left">
                  <span>{flag}</span> {lang}
                </button>
              ))}
              <div className="px-3 py-2 border-t border-gray-100">
                <p className="text-[9px] text-gray-400">Powered by Claude AI · ~3-5s</p>
              </div>
            </div>
          </>
        );
      })()}

      {/* ══ Modals ══ */}
      {showSimulator  && <Simulator nodes={nodes} edges={edges} onClose={() => setShowSimulator(false)} />}
      {showTemplates  && (
        <TemplatesModal
          onLoad={loadFlow}
          onClose={() => setShowTemplates(false)}
          onOpenAIGenerator={(type) => {
            setGeneratorTemplateType(type);
            setShowTemplates(false);
            setShowGenerator(true);
          }}
        />
      )}
      {showGenerator  && (
        <GenerateFlowModal
          onLoad={loadFlow}
          onClose={() => { setShowGenerator(false); setGeneratorTemplateType(undefined); }}
          initialTemplateType={generatorTemplateType as any}
          clinicType={clinicType}
        />
      )}
      {showHelp       && <HelpModal onClose={() => setShowHelp(false)} />}
    </div>
  );
}

/* ════════════ VALIDATOR PANEL ════════════ */
function ValidatorPanel({ validation, onClose, onHighlight }: {
  validation: ValidationResult;
  onClose: () => void;
  onHighlight: (id: string) => void;
}) {
  const ICON: Record<string,string> = { error:"❌", warning:"⚠️", tip:"💡" };
  const COLOR: Record<string,string> = { error:"#dc2626", warning:"#d97706", tip:"#6366f1" };
  const BG: Record<string,string>    = { error:"#fef2f2", warning:"#fffbeb", tip:"#eef2ff" };

  return (
    <div className="h-full flex flex-col bg-white border-l border-gray-200">
      {/* Header */}
      <div className={`px-4 py-3 border-b flex items-center gap-2 ${validation.ready?"bg-emerald-50 border-emerald-100":"bg-red-50 border-red-100"}`}>
        <span className="text-xl">{validation.ready?"✅":"❌"}</span>
        <div className="flex-1">
          <p className="font-bold text-[13px] text-gray-800">Flow Health Check</p>
          <p className={`text-[11px] font-semibold ${validation.ready?"text-emerald-600":"text-red-500"}`}>
            {validation.ready ? "Ready to deploy!" : `${validation.summary.errors} error(s) found`}
          </p>
        </div>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600">✕</button>
      </div>

      {/* Score */}
      <div className="px-4 py-3 border-b border-gray-100">
        <div className="flex items-center justify-between mb-1.5">
          <span className="text-[11px] font-bold text-gray-600">Flow Quality Score</span>
          <span className="text-[13px] font-black" style={{color: validation.score>79?"#059669":validation.score>49?"#d97706":"#dc2626"}}>
            {validation.score}/100
          </span>
        </div>
        <div className="h-2.5 bg-gray-100 rounded-full overflow-hidden">
          <div className="h-full rounded-full score-bar"
            style={{width:`${validation.score}%`, background: validation.score>79?"#059669":validation.score>49?"#d97706":"#dc2626"}} />
        </div>
        <div className="flex gap-3 mt-2 text-[10px] font-semibold">
          <span className="text-red-500">❌ {validation.summary.errors} error{validation.summary.errors!==1?"s":""}</span>
          <span className="text-amber-500">⚠️ {validation.summary.warnings} warning{validation.summary.warnings!==1?"s":""}</span>
          <span className="text-indigo-500">💡 {validation.summary.tips} tip{validation.summary.tips!==1?"s":""}</span>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-3 space-y-2">
        {validation.issues.length === 0 ? (
          <div className="text-center py-8">
            <div className="text-4xl mb-2">🎉</div>
            <p className="text-[13px] font-bold text-emerald-600">Perfect flow!</p>
            <p className="text-[11px] text-gray-400 mt-1">No issues found. Your flow is ready.</p>
          </div>
        ) : (
          validation.issues.map((issue, i) => (
            <div key={i} className="rounded-xl border overflow-hidden"
              style={{borderColor:COLOR[issue.severity]+"40", background:BG[issue.severity]}}>
              <div className="px-3 py-2">
                <div className="flex items-start gap-2">
                  <span className="text-sm flex-shrink-0">{ICON[issue.severity]}</span>
                  <div className="flex-1 min-w-0">
                    <p className="text-[11px] font-bold text-gray-800 leading-snug">{issue.message}</p>
                    {issue.nodeLabel && (
                      <p className="text-[10px] font-semibold mt-0.5" style={{color:COLOR[issue.severity]}}>
                        Block: "{issue.nodeLabel}"
                      </p>
                    )}
                    <p className="text-[10px] text-gray-500 mt-1 leading-relaxed">🔧 {issue.fix}</p>
                  </div>
                </div>
                {issue.nodeId && (
                  <button onClick={() => onHighlight(issue.nodeId!)}
                    className="mt-2 text-[10px] font-bold px-2.5 py-1 rounded-lg text-white transition"
                    style={{background:COLOR[issue.severity]}}>
                    → Select block
                  </button>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

/* ════════════ LIVE INFO PANEL ════════════ */
const TRIGGER_LABELS: Record<string, { label: string; icon: string; desc: string }> = {
  booking_created: { label: "New Booking",       icon: "📅", desc: "Fires when a new appointment is booked" },
  no_show:         { label: "No Show",            icon: "😟", desc: "Fires when a patient misses their appointment" },
  completed:       { label: "Post Treatment",     icon: "💊", desc: "Fires after a treatment is completed" },
  custom:          { label: "Custom Trigger",     icon: "⚡", desc: "Fires on your custom event" },
};

function LiveInfoPanel({ info, onClose }: {
  info: { treeName: string; triggerType: string; nodeCount: number; edgeCount: number; deployedAt: string };
  onClose: () => void;
}) {
  const trigger = TRIGGER_LABELS[info.triggerType] ?? { label: info.triggerType, icon: "⚡", desc: "Custom trigger" };
  return (
    <div className="h-full flex flex-col bg-white border-l border-gray-200 overflow-y-auto">
      {/* Header */}
      <div className="px-4 py-4 border-b border-gray-100 bg-gradient-to-r from-emerald-600 to-teal-600 flex items-start justify-between gap-2">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="w-2 h-2 rounded-full bg-white animate-pulse" />
            <span className="text-[11px] font-bold text-white/80 uppercase tracking-wider">Live on WhatsApp</span>
          </div>
          <p className="text-white font-bold text-[14px] leading-snug">{info.treeName}</p>
          <p className="text-white/60 text-[11px] mt-0.5">Deployed at {info.deployedAt}</p>
        </div>
        <button onClick={onClose} className="text-white/60 hover:text-white mt-0.5 flex-shrink-0">✕</button>
      </div>

      <div className="flex-1 p-4 space-y-4">

        {/* Trigger */}
        <div className="rounded-2xl bg-emerald-50 border border-emerald-100 p-4">
          <p className="text-[10px] font-bold text-emerald-600 uppercase tracking-wider mb-2">Trigger</p>
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-emerald-100 flex items-center justify-center text-xl flex-shrink-0">
              {trigger.icon}
            </div>
            <div>
              <p className="font-bold text-[13px] text-gray-800">{trigger.label}</p>
              <p className="text-[11px] text-gray-500 mt-0.5">{trigger.desc}</p>
            </div>
          </div>
        </div>

        {/* Flow stats */}
        <div className="rounded-2xl bg-gray-50 border border-gray-100 p-4">
          <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-3">Flow Overview</p>
          <div className="grid grid-cols-2 gap-2">
            {[
              { label: "Blocks",      value: info.nodeCount,  icon: "🧩", color: "#6366f1" },
              { label: "Connections", value: info.edgeCount,  icon: "🔗", color: "#0ea5e9" },
            ].map(s => (
              <div key={s.label} className="bg-white rounded-xl border border-gray-100 p-3 text-center">
                <p className="text-xl mb-1">{s.icon}</p>
                <p className="text-[22px] font-black" style={{ color: s.color }}>{s.value}</p>
                <p className="text-[10px] text-gray-400 font-semibold">{s.label}</p>
              </div>
            ))}
          </div>
        </div>

        {/* What happens next */}
        <div className="rounded-2xl bg-blue-50 border border-blue-100 p-4">
          <p className="text-[10px] font-bold text-blue-600 uppercase tracking-wider mb-3">What happens now</p>
          <div className="space-y-3">
            {[
              { step: "1", text: "Next time a patient triggers this flow, they'll receive your first message automatically on WhatsApp." },
              { step: "2", text: "Their replies advance them through the flow in real-time." },
              { step: "3", text: "Appointment status updates automatically based on their responses (Confirmed / Rescheduled / Cancelled)." },
            ].map(s => (
              <div key={s.step} className="flex items-start gap-3">
                <div className="w-5 h-5 rounded-full bg-blue-600 text-white flex items-center justify-center text-[10px] font-black flex-shrink-0 mt-0.5">
                  {s.step}
                </div>
                <p className="text-[11px] text-blue-800 leading-relaxed">{s.text}</p>
              </div>
            ))}
          </div>
        </div>

        {/* Quick links */}
        <div className="space-y-2">
          <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider">Quick actions</p>
          <a href="/appointments"
            className="flex items-center gap-3 p-3 rounded-xl bg-white border border-gray-100 hover:border-indigo-200 hover:bg-indigo-50 transition group">
            <span className="text-lg">📋</span>
            <div className="flex-1 min-w-0">
              <p className="text-[12px] font-bold text-gray-700 group-hover:text-indigo-700">View Appointments</p>
              <p className="text-[10px] text-gray-400">See status changes in real time</p>
            </div>
            <span className="text-gray-300 group-hover:text-indigo-400 text-[12px]">→</span>
          </a>
          <a href="/messages"
            className="flex items-center gap-3 p-3 rounded-xl bg-white border border-gray-100 hover:border-emerald-200 hover:bg-emerald-50 transition group">
            <span className="text-lg">💬</span>
            <div className="flex-1 min-w-0">
              <p className="text-[12px] font-bold text-gray-700 group-hover:text-emerald-700">Message Log</p>
              <p className="text-[10px] text-gray-400">Monitor WhatsApp delivery</p>
            </div>
            <span className="text-gray-300 group-hover:text-emerald-400 text-[12px]">→</span>
          </a>
        </div>

        {/* Status indicator */}
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-3 flex items-center gap-3">
          <div className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse flex-shrink-0" />
          <p className="text-[11px] text-emerald-700 font-semibold">
            Flow is active — new patients will enter this journey automatically
          </p>
        </div>

      </div>
    </div>
  );
}

/* ════════════ HISTORY PANEL ════════════ */
function HistoryPanel({ history, onRestore, onClose }: {
  history: {name:string;nodes:any[];edges:any[];at:string}[];
  onRestore: (snap: any) => void;
  onClose: () => void;
}) {
  return (
    <div className="h-full flex flex-col bg-white border-l border-gray-200">
      <div className="px-4 py-3 border-b border-gray-100 flex items-center gap-2">
        <span className="text-lg">🕐</span>
        <div className="flex-1">
          <p className="font-bold text-[13px] text-gray-800">Version History</p>
          <p className="text-[10px] text-gray-400">Last 5 saved versions</p>
        </div>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600">✕</button>
      </div>
      <div className="flex-1 overflow-y-auto p-3 space-y-2">
        {history.length === 0 ? (
          <div className="text-center py-10 text-gray-400">
            <div className="text-3xl mb-2">📂</div>
            <p className="text-[12px] font-semibold">No history yet</p>
            <p className="text-[10px] mt-1">Save your flow to create a version</p>
          </div>
        ) : history.map((snap, i) => (
          <div key={i} className="bg-gray-50 rounded-xl border border-gray-100 p-3">
            <div className="flex items-start gap-2">
              <div className="w-7 h-7 rounded-lg bg-slate-700 text-white flex items-center justify-center text-[10px] font-black flex-shrink-0">
                v{history.length - i}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-[12px] font-bold text-gray-800 truncate">{snap.name}</p>
                <p className="text-[10px] text-gray-400">{snap.nodes.length} blocks · saved at {snap.at}</p>
              </div>
            </div>
            <button onClick={() => onRestore(snap)}
              className="mt-2 w-full py-1.5 rounded-lg bg-slate-700 text-white text-[11px] font-bold hover:bg-slate-800 transition">
              ↩ Restore this version
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ════════════ HELP MODAL ════════════ */
function HelpModal({ onClose }: { onClose: () => void }) {
  const features = [
    { icon:"🪄", title:"AI Flow Generator", desc:"Describe your goal in plain English — Claude builds the entire chatbot flow in seconds." },
    { icon:"📋", title:"Templates Library", desc:"4 professionally designed flows (appointments, no-shows, post-treatment, onboarding) ready to load." },
    { icon:"📱", title:"WhatsApp Simulator", desc:"Preview and click through the actual conversation in a real phone UI before going live." },
    { icon:"✅", title:"Flow Health Checker", desc:"Validates your flow for errors before deploy — catches empty nodes, missing connections, dead ends." },
    { icon:"📊", title:"Analytics Overlay", desc:"Toggle the stats view to see delivery rate, response rate, and drop-off % on every block." },
    { icon:"❤️‍🔥", title:"Mood Router (Sentiment)", desc:"Claude reads patient mood and automatically routes happy/neutral/frustrated patients to different paths." },
    { icon:"🧠", title:"Memory Variables", desc:"Save patient answers (like preferred time) and reuse them in later messages as {{memory.preferred_time}}." },
    { icon:"🔄", title:"Smart Retry Gate", desc:"Auto-sends a follow-up if patient doesn't reply. Configurable delay and max retries before escalating." },
    { icon:"🌍", title:"One-Click Translation", desc:"Translate your entire flow to Arabic, French, Spanish, or Turkish in one click using Claude." },
    { icon:"🕐", title:"Version History", desc:"Every save creates a version snapshot. Restore any of the last 5 versions if you make a mistake." },
  ];
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-6 bg-black/60 backdrop-blur-sm">
      <div className="bg-white rounded-3xl shadow-2xl overflow-hidden flex flex-col" style={{width:600, maxHeight:"90vh"}}>
        <div className="bg-gradient-to-r from-indigo-600 to-violet-600 px-6 py-5 flex items-center gap-3">
          <span className="text-3xl">🌳</span>
          <div className="flex-1">
            <h2 className="text-white font-bold text-lg">10 Power Features</h2>
            <p className="text-white/70 text-[12px]">Everything you can do in Chatbot Canvas</p>
          </div>
          <button onClick={onClose} className="text-white/60 hover:text-white text-2xl p-1">✕</button>
        </div>
        <div className="flex-1 overflow-y-auto p-5 grid grid-cols-2 gap-3">
          {features.map(f => (
            <div key={f.title} className="bg-gray-50 rounded-2xl p-3 border border-gray-100">
              <div className="flex items-center gap-2 mb-1.5">
                <span className="text-xl">{f.icon}</span>
                <p className="text-[12px] font-bold text-gray-800">{f.title}</p>
              </div>
              <p className="text-[10px] text-gray-500 leading-relaxed">{f.desc}</p>
            </div>
          ))}
        </div>
        <div className="px-5 py-4 border-t border-gray-100">
          <button onClick={onClose} className="w-full py-3 bg-indigo-600 text-white rounded-2xl font-bold text-[13px] hover:bg-indigo-700 transition">
            Got it — let's build! 🚀
          </button>
        </div>
      </div>
    </div>
  );
}
