From 4dfab954d849d93ccdaee64575e0fcf8e2714d1c Mon Sep 17 00:00:00 2001 From: 3dtours Date: Thu, 6 Aug 2026 11:47:10 +0700 Subject: [PATCH] =?UTF-8?q?FIX:=20reset=20t=E1=BA=A5t=20c=E1=BA=A3=20v?= =?UTF-8?q?=E1=BB=81=20m=E1=BA=B7c=20=C4=91=E1=BB=8Bnh=20khi=20t=E1=BA=A1o?= =?UTF-8?q?=20new=20project?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/v1/auth.py | 29 ++++++++++++++++++++ app/static/js/app.jsx | 46 +++++++++++++++++++++++++++++--- app/static/js/app.precompiled.js | 6 ++++- app/templates/index.html | 2 +- wiki.md | 26 ++++++++++++++++++ 5 files changed, 104 insertions(+), 5 deletions(-) diff --git a/app/api/v1/auth.py b/app/api/v1/auth.py index dad00bd..4390d4e 100644 --- a/app/api/v1/auth.py +++ b/app/api/v1/auth.py @@ -259,3 +259,32 @@ async def get_profile(current_user: dict = Depends(get_current_user)): "max_tracks": row["max_tracks"] or 16 } } + + +@router.get("/first-time") +async def auth_first_time(): + # "Lần đăng nhập đầu" = tài khoản admin vẫn dùng mật khẩu MẶC ĐỊNH + # (chưa từng đổi). Sau khi đổi lần đầu → first_time = false → UI xóa + # gợi ý username/mật khẩu (Tùy chọn - Admin có thể bỏ trống, lần đầu: + # admin123, nút Điền nhanh). + try: + conn = get_db_connection() + try: + cur = conn.cursor() + cur.execute( + "SELECT id, hashed_password, must_change_password FROM users " + "WHERE LOWER(role) = 'admin' ORDER BY created_at ASC LIMIT 1" + ) + row = cur.fetchone() + finally: + conn.close() + if not row: + return {"first_time": True} + still_default = False + try: + still_default = verify_password("admin123", row["hashed_password"]) + except Exception: + still_default = False + return {"first_time": bool(row["must_change_password"]) and still_default} + except Exception: + return {"first_time": True} diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index e885477..6877ce7 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -4850,12 +4850,27 @@ const AuthModal = ({ const [newPassword, setNewPassword] = useState(''); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); + const [firstTime, setFirstTime] = useState(true); useEffect(() => { if (mode) setActiveTab(mode); if (mode === 'force_change' && !oldPassword) { setOldPassword('admin123'); } }, [mode]); + // Lần đăng nhập ĐẦU (admin còn mật khẩu mặc định) → hiện gợi ý + // username/mật khẩu; sau khi đã đổi → ẩn vĩnh viễn. + useEffect(() => { + if (!isOpen) return; + if (window.SonicAPI && window.SonicAPI.apiRequest) { + window.SonicAPI.apiRequest('/api/v1/auth/first-time', { method: 'GET' }) + .then(function (d) { setFirstTime(!!(d && d.first_time)); }) + // Fail-closed: endpoint lỗi/404 (backend chưa restart) → ẨN gợi ý + // (không hiện — user đã yêu cầu bỏ gợi ý sau lần đầu). + .catch(function () { setFirstTime(false); }); + } else { + setFirstTime(false); + } + }, [isOpen]); const handleSubmit = async e => { e.preventDefault(); setError(''); @@ -4930,7 +4945,7 @@ const AuthModal = ({ className: "w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500" }))) : /*#__PURE__*/React.createElement(React.Fragment, null, activeTab === 'login' ? /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("label", { className: "block text-xs font-semibold mb-1 text-slate-400" - }, "Tên đăng nhập ", /*#__PURE__*/React.createElement("span", { + }, "Tên đăng nhập ", firstTime && /*#__PURE__*/React.createElement("span", { className: "text-teal-400 font-normal" }, "(Tùy chọn - Admin có thể bỏ trống)")), /*#__PURE__*/React.createElement("input", { type: "text", @@ -4956,7 +4971,7 @@ const AuthModal = ({ className: "w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500" })), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("label", { className: "block text-xs font-semibold mb-1 text-slate-400" - }, "Mật khẩu ", activeTab === 'login' && /*#__PURE__*/React.createElement("span", { + }, "Mật khẩu ", activeTab === 'login' && firstTime && /*#__PURE__*/React.createElement("span", { className: "text-amber-400 font-normal" }, "(Lần đầu: admin123)")), /*#__PURE__*/React.createElement("input", { type: "password", @@ -4969,7 +4984,7 @@ const AuthModal = ({ type: "submit", disabled: loading, className: "w-full py-2 bg-teal-600 hover:bg-teal-500 text-white font-semibold rounded-lg shadow transition duration-150" - }, loading ? 'Đang xác thực...' : isForceMode ? 'Đổi Mật Khẩu Ngay' : activeTab === 'login' ? 'Đăng Nhập System' : 'Tạo Tài Khoản Mới'), activeTab === 'login' && !isForceMode && /*#__PURE__*/React.createElement("button", { + }, loading ? 'Đang xác thực...' : isForceMode ? 'Đổi Mật Khẩu Ngay' : activeTab === 'login' ? 'Đăng Nhập System' : 'Tạo Tài Khoản Mới'), activeTab === 'login' && !isForceMode && firstTime && /*#__PURE__*/React.createElement("button", { type: "button", onClick: () => { setUsername('admin'); @@ -15832,6 +15847,16 @@ const App = () => { } if (ctrl && !alt && e.key === 'n') { e.preventDefault(); + // New project: đóng hết tab + reset MỌI trạng thái về mặc định + try { stopAllPlayback(); } catch (e) {} + setSubTabs([]); + setSessionTabs([]); + setActiveTab('main'); + trackMidiChannelsRef.current = {}; + Object.keys(trackMidiBypassMap).forEach(function (k) { delete trackMidiBypassMap[k]; }); + Object.keys(trackAudioBypassMap).forEach(function (k) { delete trackAudioBypassMap[k]; }); + Object.keys(trackMasteringBypassMap).forEach(function (k) { delete trackMasteringBypassMap[k]; }); + setSelectedItemIds(new Set()); setTracks([{ id: '1', name: 'Track 01', @@ -15858,6 +15883,10 @@ const App = () => { serverFileId: null }]); setSelectedTrackId('1'); + setProjectName(''); + setCurrentProjectId(null); + localStorage.removeItem('sonic_project_name'); + localStorage.removeItem('sonic_project_id'); showToast('New project created', 'info'); return; } @@ -24388,6 +24417,17 @@ STRICT CONSTRAINTS: icon: 'file-plus', shortcut: 'Ctrl+N', action: () => { + // New project: đóng hết tab + reset MỌI trạng thái về mặc định + try { stopAllPlayback(); } catch (e) {} + setSubTabs([]); + setSessionTabs([]); + setActiveTab('main'); + // Reset instrument/channel/route context đã load + trackMidiChannelsRef.current = {}; + Object.keys(trackMidiBypassMap).forEach(function (k) { delete trackMidiBypassMap[k]; }); + Object.keys(trackAudioBypassMap).forEach(function (k) { delete trackAudioBypassMap[k]; }); + Object.keys(trackMasteringBypassMap).forEach(function (k) { delete trackMasteringBypassMap[k]; }); + setSelectedItemIds(new Set()); setTracks([{ id: '1', name: 'Track 01', diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index fe8fd80..dc3feaf 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -325,7 +325,11 @@ let working=[...merged];let dragIdx=working.findIndex(n=>n.time===newNode.time&& subTabAnchorRef.current=startTime;setSelectedNodeTime(null);onSelectRange(startTime,startTime);onPlayheadSet(startTime);const handleMouseMove=moveEvent=>{const currentX=moveEvent.clientX-rect.left+scrollLeft;const ct=Math.max(0,Math.min(wallDuration,currentX/zoom));const anchor=subTabAnchorRef.current??startTime;onSelectRange(Math.min(anchor,ct),Math.max(anchor,ct));};const handleMouseUp=()=>{document.removeEventListener('mousemove',handleMouseMove);document.removeEventListener('mouseup',handleMouseUp);};document.addEventListener('mousemove',handleMouseMove);document.addEventListener('mouseup',handleMouseUp);};const handleContextMenuInternal=e=>{e.preventDefault();e.stopPropagation();const canvas=canvasRef.current;const rect=canvas.getBoundingClientRect();const parent=canvas.parentElement;const scrollContainer=parent?parent.parentElement:null;const scrollLeft=scrollContainer?scrollContainer.scrollLeft:0;const x=e.clientX-rect.left+scrollLeft;const clickTime=Math.max(0,Math.min(buffer.duration/(speed||1.0),x/zoom));onContextMenu(e,clickTime);};// Double-click on automation curve to create a new node const handleDoubleClick=e=>{const canvas=canvasRef.current;if(!canvas||!buffer)return;if(activeTool!=='select'&&activeTool!=='pen')return;const rect=canvas.getBoundingClientRect();const parent=canvas.parentElement;const scrollContainer=parent?parent.parentElement:null;const scrollLeft=scrollContainer?scrollContainer.scrollLeft:0;const x=e.clientX-rect.left+scrollLeft;const clickTime=Math.max(0,Math.min(buffer.duration/(speed||1.0),x/zoom));const isPan=(graphMode||'volume')==='pan';const curNodes=isPan?panningNodes:volumeNodes;const cTop=8;const cHeight=rect.height-16;const valFromY=y=>{if(isPan)return Math.max(-1,Math.min(1,-(y-cTop)/cHeight*2+1));const yOff=(y-cTop)/cHeight;return yOff<=2/3?Math.max(0,Math.min(3,3*(1-yOff*3/2))):Math.max(-30,Math.min(0,-30*(yOff-2/3)*3));};// Interpolate value at click position from existing curve let interpolatedVal=valFromY(e.clientY-rect.top);if(curNodes.length>=2){const sorted=[...curNodes].sort((a,b)=>a.time-b.time);for(let i=0;i=sorted[i].time&&clickTime<=sorted[i+1].time){const t=(clickTime-sorted[i].time)/(sorted[i+1].time-sorted[i].time);const v1=isPan?sorted[i].pan:sorted[i].db;const v2=isPan?sorted[i+1].pan:sorted[i+1].db;interpolatedVal=v1+t*(v2-v1);break;}}}const newNode=isPan?{time:+Math.round(clickTime*10)/10,pan:+Math.round(interpolatedVal*20)/20}:{time:+Math.round(clickTime*10)/10,db:+Math.round(interpolatedVal*2)/2};const merged=(()=>{const map=new Map();curNodes.forEach(n=>map.set(n.time,n));map.set(newNode.time,newNode);return Array.from(map.values()).sort((a,b)=>a.time-b.time);})();if(onUpdateNodes)onUpdateNodes(merged);};return/*#__PURE__*/React.createElement("div",{style:{width:`${timelineWidth}px`,height:'100%',position:'relative',overflow:'hidden'}},/*#__PURE__*/React.createElement("canvas",{ref:canvasRef,style:{position:'absolute',top:0,left:0,imageRendering:'pixelated'},className:"cursor-crosshair rounded border border-zinc-800",onMouseDown:handleMouseDown,onDoubleClick:handleDoubleClick,onContextMenu:handleContextMenuInternal,onMouseMove:e=>{if(canvasRef.current&&e.altKey&&onSpeedChange){const rect=canvasRef.current.getBoundingClientRect();const parent=canvasRef.current.parentElement;const scrollContainer=parent?parent.parentElement:null;const scrollLeft=scrollContainer?scrollContainer.scrollLeft:0;const mx=e.clientX-rect.left+scrollLeft;const wClip=buffer.duration/speed*zoom;const tolerance=8;canvasRef.current.style.cursor=Math.abs(mx-wClip)<=tolerance&&!isStretchingRef.current?'ew-resize':'crosshair';}else if(canvasRef.current&&!isStretchingRef.current){const rect=canvasRef.current.getBoundingClientRect();const parent=canvasRef.current.parentElement;const scrollContainer=parent?parent.parentElement:null;const scrollLeft=scrollContainer?scrollContainer.scrollLeft:0;const mx=e.clientX-rect.left+scrollLeft;const wClipPx=buffer.duration/(speed||1.0)*zoom;const cH=canvasRef.current.height/(window.devicePixelRatio||1)-16;const btnX=wClipPx-28-4;const btnY=8+cH-14-2;const overBtn=mx>=btnX&&mx<=btnX+28&&e.clientY-rect.top>=btnY&&e.clientY-rect.top<=btnY+14;canvasRef.current.style.cursor=overBtn?'pointer':'crosshair';}}}));};const SubTabToolbar=({st,activeTool,setActiveTool,handleSubTabNormalizeWithValue,handleSubTabGainWithValue,handleSubTabPitch,handleSubTabStretch,handleSubTabFade,onPlayPause,onStop,onRewind,onForward,onLoop,onRecord,onRateChange,onCut,onCopy,onPaste,onGlue,snapValue,onSnapChange})=>{const isPlaying=st?.isPlaying||false;const isLooping=st?.isLooping||false;const isRecording=st?.isRecording||false;return/*#__PURE__*/React.createElement("div",{className:"daw-header flex h-16 items-center px-4 border-b daw-border gap-3 bg-zinc-800"},/*#__PURE__*/React.createElement("div",{className:"flex items-center space-x-1 border-r border-zinc-700 pr-3"},/*#__PURE__*/React.createElement("button",{className:`p-1 rounded ${activeTool==='select'?'bg-cyan-700':'bg-zinc-700'}`,onClick:()=>setActiveTool('select'),title:"Select Tool"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"mouse-pointer",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("button",{className:`p-1 rounded ${activeTool==='grab'?'bg-cyan-700':'bg-zinc-700'}`,onClick:()=>setActiveTool('grab'),title:"Grab Tool"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"hand",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("button",{className:`p-1 rounded ${activeTool==='razor'?'bg-cyan-700':'bg-zinc-700'}`,onClick:()=>setActiveTool('razor'),title:"Razor Tool"},/*#__PURE__*/React.createElement("svg",{className:"w-4 h-4 text-orange-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},/*#__PURE__*/React.createElement("path",{d:"M6 3h12a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}),/*#__PURE__*/React.createElement("path",{d:"M4 9h16l-3 9H7z"}),/*#__PURE__*/React.createElement("circle",{cx:"12",cy:"6",r:"1"}))),/*#__PURE__*/React.createElement("button",{className:`p-1 rounded ${activeTool==='pen'?'bg-cyan-700':'bg-zinc-700'}`,onClick:()=>setActiveTool('pen'),title:"Pen Tool"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"pen-tool",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("div",{className:"w-[1px] h-4 bg-zinc-800 mx-0.5"}),/*#__PURE__*/React.createElement("button",{onClick:onGlue,className:"p-0.5 rounded text-zinc-400 hover:bg-zinc-800 hover:text-purple-400 transition",title:"Glue Clips"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"link",className:"w-3.5 h-3.5"}))),/*#__PURE__*/React.createElement("button",{onClick:onCut,className:"p-0.5 rounded text-zinc-400 hover:bg-zinc-800 hover:text-red-400 transition",title:"Cut (Ctrl+X)"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"scissors",className:"w-3.5 h-3.5"}))),/*#__PURE__*/React.createElement("button",{onClick:onCopy,className:"p-0.5 rounded text-zinc-400 hover:bg-zinc-800 hover:text-blue-400 transition",title:"Copy (Ctrl+C)"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"copy",className:"w-3.5 h-3.5"}))),/*#__PURE__*/React.createElement("button",{onClick:onPaste,className:"p-0.5 rounded text-zinc-400 hover:bg-zinc-800 hover:text-emerald-400 transition",title:"Paste (Ctrl+V)"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"clipboard",className:"w-3.5 h-3.5"})))),/*#__PURE__*/React.createElement("div",{className:"flex items-center gap-1 border-r border-zinc-700 pr-3"},/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-500 font-bold uppercase"},"Snap"),/*#__PURE__*/React.createElement("select",{value:snapValue||'free',onChange:e=>onSnapChange(e.target.value),className:"bg-zinc-850 text-zinc-300 text-xs px-1 py-0.5 rounded border border-zinc-800 focus:outline-none font-mono"},/*#__PURE__*/React.createElement("option",{value:"free"},"Free"),/*#__PURE__*/React.createElement("option",{value:"4"},"4"),/*#__PURE__*/React.createElement("option",{value:"1"},"1"),/*#__PURE__*/React.createElement("option",{value:"1/2"},"1/2"),/*#__PURE__*/React.createElement("option",{value:"1/4"},"1/4"),/*#__PURE__*/React.createElement("option",{value:"1/8"},"1/8"),/*#__PURE__*/React.createElement("option",{value:"1/16"},"1/16"),/*#__PURE__*/React.createElement("option",{value:"1/32"},"1/32"))),/*#__PURE__*/React.createElement("div",{className:"flex items-center space-x-2 flex-1 overflow-x-auto no-scrollbar"},/*#__PURE__*/React.createElement("div",{className:"flex items-center gap-1"},/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-400"},"Normalize:"),/*#__PURE__*/React.createElement("input",{type:"range",min:"-12",max:"0",value:st.effects?.normalizeDb||0,step:"0.1",onChange:e=>handleSubTabNormalizeWithValue(st.id,parseFloat(e.target.value)),className:"w-20 h-1.5"}),/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-500 w-10 text-right"},st.effects?.normalizeDb||0," dB")),/*#__PURE__*/React.createElement("div",{className:"flex items-center gap-1"},/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-400"},"Gain:"),/*#__PURE__*/React.createElement("input",{type:"range",min:"-40",max:"24",value:st.effects?.gainDb||0,step:"0.1",onChange:e=>handleSubTabGainWithValue(st.id,parseFloat(e.target.value)),className:"w-20 h-1.5"}),/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-500 w-10 text-right"},st.effects?.gainDb||0," dB")),/*#__PURE__*/React.createElement("div",{className:"flex items-center gap-1"},/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-400"},"Pitch:"),/*#__PURE__*/React.createElement("input",{type:"range",min:"-12",max:"12",value:st.effects?.pitch||0,step:"0.1",onChange:e=>handleSubTabPitch(st.id,parseFloat(e.target.value)),className:"w-20 h-1.5"}),/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-500 w-10 text-right"},st.effects?.pitch||0," st")),/*#__PURE__*/React.createElement("div",{className:"flex items-center gap-1"},/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-400"},"Stretch:"),/*#__PURE__*/React.createElement("input",{type:"range",min:"50",max:"200",value:st.effects?.speedStretch||100,step:"1",onChange:e=>handleSubTabStretch(st.id,parseInt(e.target.value)),className:"w-20 h-1.5"}),/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-500 w-10 text-right"},st.effects?.speedStretch||100,"%"))),/*#__PURE__*/React.createElement("div",{className:"flex items-center space-x-1 border-r border-zinc-700 pr-3"},/*#__PURE__*/React.createElement("button",{onClick:()=>handleSubTabFade(st.id,'in'),className:"px-2 py-1 text-xs rounded hover:bg-zinc-700"},"Fade In"),/*#__PURE__*/React.createElement("button",{onClick:()=>handleSubTabFade(st.id,'out'),className:"px-2 py-1 text-xs rounded hover:bg-zinc-700"},"Fade Out")),/*#__PURE__*/React.createElement("div",{className:"flex items-center space-x-1 border-r border-zinc-700 pr-3"},/*#__PURE__*/React.createElement("button",{onClick:onRewind,className:"w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition",title:"Rewind"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"skip-back",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("button",{onClick:onPlayPause,className:`w-8 h-8 flex items-center justify-center rounded border transition ${isPlaying?'bg-emerald-600 text-black border-emerald-500 hover:bg-emerald-500':'bg-cyan-600 text-white border-cyan-500 hover:bg-cyan-500'}`,title:isPlaying?"Pause":"Play"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":isPlaying?'pause':'play',className:"w-4 h-4 fill-current"}))),/*#__PURE__*/React.createElement("button",{onClick:onStop,className:"w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition",title:"Stop"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"square",className:"w-4 h-4 fill-current"}))),/*#__PURE__*/React.createElement("button",{onClick:onForward,className:"w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition",title:"Forward"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"skip-forward",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("button",{onClick:onLoop,className:`w-8 h-8 flex items-center justify-center rounded border transition ${isLooping?'bg-amber-600 text-black border-amber-500 hover:bg-amber-500':'bg-zinc-800 text-zinc-200 border-zinc-700 hover:bg-zinc-700'}`,title:isLooping?"Loop On":"Loop Off"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"repeat",className:"w-4 h-4"}))),/*#__PURE__*/React.createElement("button",{onClick:onRecord,className:`w-8 h-8 flex items-center justify-center rounded border transition ${isRecording?'bg-red-600 text-white border-red-500':'bg-zinc-800 text-zinc-200 border-zinc-700 hover:bg-zinc-700'}`,title:isRecording?"Recording":"Record"},/*#__PURE__*/React.createElement("span",{className:"inline-flex items-center shrink-0"},/*#__PURE__*/React.createElement("i",{"data-lucide":"circle",className:"w-4 h-4"})))),/*#__PURE__*/React.createElement("div",{className:"flex items-center space-x-1"},/*#__PURE__*/React.createElement("span",{className:"text-xs text-zinc-400"},"Rate:"),/*#__PURE__*/React.createElement("select",{value:st.playbackRate||1,onChange:e=>onRateChange(parseFloat(e.target.value)),className:"bg-zinc-700 text-zinc-100 text-xs px-1 py-0.5 rounded border border-zinc-600"},/*#__PURE__*/React.createElement("option",{value:"0.5"},"0.5x"),/*#__PURE__*/React.createElement("option",{value:"0.75"},"0.75x"),/*#__PURE__*/React.createElement("option",{value:"1"},"1x"),/*#__PURE__*/React.createElement("option",{value:"1.25"},"1.25x"),/*#__PURE__*/React.createElement("option",{value:"1.5"},"1.5x"),/*#__PURE__*/React.createElement("option",{value:"2"},"2x"))));};// ── Graph Editor Canvas for Volume/Pan/Fade Automation ── -const GraphEditorCanvas=({buffer,zoom,timelineWidth,volumeNodes,panningNodes,fadeInLen,fadeOutLen,onUpdateNodes,graphMode})=>{const canvasRef=useRef(null);const isDraggingNode=useRef(false);const dragNodeIdx=useRef(-1);const isCreatingNode=useRef(false);const getNodes=()=>graphMode==='pan'?panningNodes:volumeNodes;const nodeLabel=n=>graphMode==='pan'?`${n.pan.toFixed(2)}`:`${n.db.toFixed(1)}dB`;const nodeY=(n,h)=>{if(graphMode==='pan')return(1-(n.pan+1)/2)*h;const zeroY=2/3*h;return n.db>=0?zeroY-n.db/3*(2/3*h):zeroY+-n.db/30*(1/3*h);};const nodeValFromY=(y,h)=>{if(graphMode==='pan')return-(y/h*2-1);const yOff=y/h;return yOff<=2/3?3*(1-yOff*3/2):-30*(yOff-2/3)*3;};useEffect(()=>{const canvas=canvasRef.current;if(!canvas||!buffer)return;const ctx=canvas.getContext('2d');const dpr=window.devicePixelRatio||1;const wrapper=canvas.parentElement?canvas.parentElement.parentElement:null;const scrollLeft=wrapper?wrapper.scrollLeft:0;const vWidth=wrapper?wrapper.clientWidth:1200;const drawWidth=Math.min(timelineWidth,Math.max(vWidth,1200));const h=canvas.parentElement?canvas.parentElement.clientHeight:200;canvas.width=Math.round(drawWidth*dpr);canvas.height=Math.round(h*dpr);ctx.scale(dpr,dpr);ctx.imageSmoothingEnabled=false;canvas.style.position='absolute';canvas.style.left=`${scrollLeft}px`;canvas.style.width=`${drawWidth}px`;canvas.style.height=`${h}px`;ctx.fillStyle='#1a1a2e';ctx.fillRect(0,0,drawWidth,h);ctx.strokeStyle='#2a2a4e';ctx.lineWidth=0.5;for(let t=0;t<=buffer.duration;t+=0.5){const x=t/buffer.duration*drawWidth;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,h);ctx.stroke();}for(let i=0;i<=10;i++){const y=i/10*h;ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(drawWidth,y);ctx.stroke();}if(fadeInLen>0){const fadeX=fadeInLen/buffer.duration*drawWidth;ctx.fillStyle='rgba(16, 185, 129, 0.12)';ctx.fillRect(0,0,fadeX,h);}if(fadeOutLen>0){const fadeX=(buffer.duration-fadeOutLen)/buffer.duration*drawWidth;const fadeW=fadeOutLen/buffer.duration*drawWidth;ctx.fillStyle='rgba(239, 68, 68, 0.12)';ctx.fillRect(fadeX,0,fadeW,h);}const nodes=getNodes();if(nodes.length>0){ctx.strokeStyle=graphMode==='pan'?'#a855f7':'#06b6d4';ctx.lineWidth=2;ctx.beginPath();nodes.forEach((n,i)=>{const x=n.time/buffer.duration*drawWidth;const y=nodeY(n,h);if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);});ctx.stroke();nodes.forEach((n,i)=>{const x=n.time/buffer.duration*drawWidth;const y=nodeY(n,h);ctx.fillStyle=graphMode==='pan'?'#a855f7':'#06b6d4';ctx.beginPath();ctx.arc(x,y,5,0,Math.PI*2);ctx.fill();ctx.fillStyle='#e4e4e7';ctx.font='9px monospace';ctx.fillText(nodeLabel(n),x+8,y+3);});}else{ctx.fillStyle='#52525b';ctx.font='11px sans-serif';ctx.textAlign='center';ctx.fillText(graphMode==='pan'?'Click to add Pan points':'Click to add Volume points',drawWidth/2,h/2);ctx.textAlign='start';}const zeroY=graphMode==='pan'?h/2:nodeY({db:0},h);ctx.strokeStyle=graphMode==='pan'?'#a855f744':'#06b6d444';ctx.lineWidth=1;ctx.setLineDash([4,4]);ctx.beginPath();ctx.moveTo(0,zeroY);ctx.lineTo(drawWidth,zeroY);ctx.stroke();ctx.setLineDash([]);},[buffer,zoom,timelineWidth,volumeNodes,panningNodes,fadeInLen,fadeOutLen,graphMode]);const handleMouseDown=e=>{const canvas=canvasRef.current;if(!canvas||!buffer)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const time=x/rect.width*buffer.duration;const val=nodeValFromY(y,rect.height);const nodes=getNodes();const snapped=Math.max(-30,Math.min(3,val));const snappedPan=Math.max(-1,Math.min(1,val));const threshold=12/rect.width*buffer.duration;const nearIdx=nodes.findIndex(n=>Math.abs(n.time-time)=0){isDraggingNode.current=true;dragNodeIdx.current=nearIdx;return;}const newNode=graphMode==='pan'?{time:+time.toFixed(3),pan:+snappedPan.toFixed(2)}:{time:+time.toFixed(3),db:+snapped.toFixed(1)};const sorted=[...nodes,newNode].sort((a,b)=>a.time-b.time);onUpdateNodes(sorted);const rearrangeNewIdx=sorted.findIndex(n=>n.time===newNode.time&&(graphMode==='pan'?n.pan:n.db)===(graphMode==='pan'?newNode.pan:newNode.db));isDraggingNode.current=true;dragNodeIdx.current=rearrangeNewIdx;isCreatingNode.current=true;};const handleMouseMove=e=>{if(!isDraggingNode.current||dragNodeIdx.current<0)return;const canvas=canvasRef.current;if(!canvas)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const time=Math.max(0,Math.min(buffer.duration,x/rect.width*buffer.duration));const val=nodeValFromY(y,rect.height);const nodes=[...getNodes()];nodes[dragNodeIdx.current]=graphMode==='pan'?{time:+time.toFixed(3),pan:+Math.max(-1,Math.min(1,val)).toFixed(2)}:{time:+time.toFixed(3),db:+Math.max(-30,Math.min(3,val)).toFixed(1)};onUpdateNodes(nodes.sort((a,b)=>a.time-b.time));};const handleMouseUp=()=>{isDraggingNode.current=false;dragNodeIdx.current=-1;isCreatingNode.current=false;};const handleContextMenu=e=>{e.preventDefault();const canvas=canvasRef.current;if(!canvas||!buffer)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const time=x/rect.width*buffer.duration;const threshold=12/rect.width*buffer.duration;const nodes=getNodes();const nearIdx=nodes.findIndex(n=>Math.abs(n.time-time)=0)onUpdateNodes(nodes.filter((_,i)=>i!==nearIdx));};return/*#__PURE__*/React.createElement("div",{style:{width:`${timelineWidth}px`,height:'100%',position:'relative',overflow:'hidden'}},/*#__PURE__*/React.createElement("canvas",{ref:canvasRef,style:{position:'absolute',top:0,left:0,imageRendering:'pixelated'},className:"cursor-crosshair rounded border border-zinc-700",onMouseDown:handleMouseDown,onMouseMove:handleMouseMove,onMouseUp:handleMouseUp,onMouseLeave:handleMouseUp,onContextMenu:handleContextMenu}));};const AuthModal=({isOpen,mode,forceMandatory,onClose,onSuccess})=>{if(!isOpen)return null;const[activeTab,setActiveTab]=useState(mode||'login');const[username,setUsername]=useState('admin');const[email,setEmail]=useState('');const[password,setPassword]=useState('');const[oldPassword,setOldPassword]=useState('');const[newPassword,setNewPassword]=useState('');const[error,setError]=useState('');const[loading,setLoading]=useState(false);useEffect(()=>{if(mode)setActiveTab(mode);if(mode==='force_change'&&!oldPassword){setOldPassword('admin123');}},[mode]);const handleSubmit=async e=>{e.preventDefault();setError('');setLoading(true);try{if(activeTab==='login'){const targetUsername=username.trim()||'admin';const targetPwd=password.trim()||'admin123';const res=await window.SonicAPI.login(targetUsername,targetPwd);localStorage.setItem('sonic_token',res.access_token);localStorage.setItem('sonic_user',JSON.stringify(res.user));if(res.user&&res.user.must_change_password){setOldPassword(targetPwd);}onSuccess(res.user,res.access_token);}else if(activeTab==='register'){const res=await window.SonicAPI.register(username.trim(),email.trim(),password.trim());localStorage.setItem('sonic_token',res.access_token);localStorage.setItem('sonic_user',JSON.stringify(res.user));onSuccess(res.user,res.access_token);}else if(activeTab==='force_change'){const res=await window.SonicAPI.changePassword(oldPassword.trim(),newPassword.trim());localStorage.setItem('sonic_token',res.access_token);const user=JSON.parse(localStorage.getItem('sonic_user')||'{}');user.must_change_password=false;localStorage.setItem('sonic_user',JSON.stringify(user));onSuccess(user,res.access_token);}}catch(err){setError(err.message||(activeTab==='login'?'Tài khoản hoặc mật khẩu không chính xác. (Nếu bạn đã đổi mật khẩu trước đó, vui lòng nhập mật khẩu mới mà bạn đã tạo)':'Thao tác không thành công'));}finally{setLoading(false);}};const isForceMode=activeTab==='force_change';const canClose=!forceMandatory&&!isForceMode;return/*#__PURE__*/React.createElement("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md"},/*#__PURE__*/React.createElement("div",{className:"bg-[#262626] border border-[#383838] rounded-xl shadow-2xl w-full max-w-md p-6 text-slate-200"},/*#__PURE__*/React.createElement("div",{className:"flex justify-between items-center pb-4 border-b border-[#383838]"},/*#__PURE__*/React.createElement("h3",{className:"text-lg font-bold text-teal-400"},isForceMode?'⚠️ Bắt Buộc Đổi Mật Khẩu Khởi Tạo':activeTab==='login'?'🔐 Đăng Nhập Hệ Thống':'📝 Đăng Ký Tài Khoản'),canClose&&/*#__PURE__*/React.createElement("button",{onClick:onClose,className:"text-slate-400 hover:text-slate-200"},"✕")),error&&/*#__PURE__*/React.createElement("div",{className:"mt-4 p-3 bg-red-900/40 border border-red-700 rounded-lg text-red-200 text-sm"},error),/*#__PURE__*/React.createElement("form",{onSubmit:handleSubmit,className:"mt-4 space-y-4"},isForceMode?/*#__PURE__*/React.createElement(React.Fragment,null,/*#__PURE__*/React.createElement("p",{className:"text-xs text-amber-400 bg-amber-950/60 p-2.5 border border-amber-800/80 rounded leading-relaxed"},"🔒 Tài khoản của bạn đang dùng mật khẩu khởi tạo mặc định. Để bảo mật hệ thống, bạn phải đổi mật khẩu mới trước khi tiếp tục."),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Mật khẩu hiện tại (Mặc định: admin123)"),/*#__PURE__*/React.createElement("input",{type:"password",autoComplete:"current-password",required:true,value:oldPassword,onChange:e=>setOldPassword(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Mật khẩu mới"),/*#__PURE__*/React.createElement("input",{type:"password",autoComplete:"new-password",required:true,value:newPassword,onChange:e=>setNewPassword(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"}))):/*#__PURE__*/React.createElement(React.Fragment,null,activeTab==='login'?/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Tên đăng nhập ",/*#__PURE__*/React.createElement("span",{className:"text-teal-400 font-normal"},"(Tùy chọn - Admin có thể bỏ trống)")),/*#__PURE__*/React.createElement("input",{type:"text",placeholder:"Mặc định: admin",value:username,onChange:e=>setUsername(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})):/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Tên đăng nhập"),/*#__PURE__*/React.createElement("input",{type:"text",required:true,value:username,onChange:e=>setUsername(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})),activeTab==='register'&&/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Email"),/*#__PURE__*/React.createElement("input",{type:"email",required:true,value:email,onChange:e=>setEmail(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Mật khẩu ",activeTab==='login'&&/*#__PURE__*/React.createElement("span",{className:"text-amber-400 font-normal"},"(Lần đầu: admin123)")),/*#__PURE__*/React.createElement("input",{type:"password",autoComplete:activeTab==='login'?'current-password':'new-password',required:true,value:password,onChange:e=>setPassword(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"}))),/*#__PURE__*/React.createElement("button",{type:"submit",disabled:loading,className:"w-full py-2 bg-teal-600 hover:bg-teal-500 text-white font-semibold rounded-lg shadow transition duration-150"},loading?'Đang xác thực...':isForceMode?'Đổi Mật Khẩu Ngay':activeTab==='login'?'Đăng Nhập System':'Tạo Tài Khoản Mới'),activeTab==='login'&&!isForceMode&&/*#__PURE__*/React.createElement("button",{type:"button",onClick:()=>{setUsername('admin');setPassword('admin123');setError('');},className:"w-full mt-2 py-1.5 bg-amber-950/60 hover:bg-amber-900/80 text-amber-300 border border-amber-800/60 text-xs font-semibold rounded-lg transition flex items-center justify-center gap-1.5"},"🔑 Điền Nhanh Tài Khoản Admin (admin / admin123)")),!isForceMode&&/*#__PURE__*/React.createElement("div",{className:"mt-4 pt-4 border-t border-[#383838] text-center text-xs text-slate-400"},activeTab==='login'?/*#__PURE__*/React.createElement("span",null,"Chưa có tài khoản? ",/*#__PURE__*/React.createElement("button",{onClick:()=>setActiveTab('register'),className:"text-teal-400 hover:underline"},"Đăng ký ngay")):/*#__PURE__*/React.createElement("span",null,"Đã có tài khoản? ",/*#__PURE__*/React.createElement("button",{onClick:()=>setActiveTab('login'),className:"text-teal-400 hover:underline"},"Đăng nhập")))));};const AIConfigModal=({isOpen,onClose,onConfigSaved})=>{if(!isOpen)return null;const defaultProvidersList=[{id:'openai_default',name:'OpenAI Official',provider_type:'openai',api_base_url:'https://api.openai.com/v1',api_key:'',model_name:'gpt-4o',temperature:0.7,is_active:true},{id:'openai_compat_default',name:'OpenAI Compatible (Ollama/LocalAI/DeepSeek)',provider_type:'openai_compatible',api_base_url:'http://localhost:11434/v1',api_key:'ollama',model_name:'deepseek-r1',temperature:0.7,is_active:false},{id:'anthropic_default',name:'Anthropic Claude',provider_type:'anthropic',api_base_url:'https://api.anthropic.com/v1',api_key:'',model_name:'claude-3-5-sonnet',temperature:0.7,is_active:false},{id:'gemini_default',name:'Google Gemini',provider_type:'gemini',api_base_url:'https://generativelanguage.googleapis.com',api_key:'',model_name:'gemini-1.5-pro',temperature:0.7,is_active:false}];const[providers,setProviders]=useState(defaultProvidersList);const[selectedId,setSelectedId]=useState('openai_default');const[msg,setMsg]=useState('');const[error,setError]=useState('');const[loading,setLoading]=useState(false);useEffect(()=>{if(isOpen)loadConfigs();},[isOpen]);const loadConfigs=async()=>{setLoading(true);setError('');try{const data=await window.SonicAPI.getAIConfigs();if(data&&data.providers){setProviders(data.providers);if(data.providers.length>0)setSelectedId(data.providers[0].id);}}catch(err){setError(err.message||'Lỗi nạp cấu hình AI');}finally{setLoading(false);}};const handleSave=async e=>{e.preventDefault();setMsg('');setError('');setLoading(true);try{const res=await window.SonicAPI.saveAIConfigs(providers);setMsg(res.message||'Đã lưu cấu hình AI Providers thành công!');if(onConfigSaved)onConfigSaved(providers);}catch(err){setError(err.message||'Lỗi khi lưu cấu hình AI');}finally{setLoading(false);}};const updateProviderField=(id,field,value)=>{setProviders(prev=>prev.map(p=>p.id===id?{...p,[field]:value}:p));};const activeProvider=providers.find(p=>p.id===selectedId)||providers[0];return/*#__PURE__*/React.createElement("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm select-none"},/*#__PURE__*/React.createElement("div",{className:"bg-[#262626] border border-[#383838] rounded-xl shadow-2xl w-full max-w-2xl p-6 text-slate-200"},/*#__PURE__*/React.createElement("div",{className:"flex justify-between items-center pb-4 border-b border-[#383838]"},/*#__PURE__*/React.createElement("h3",{className:"text-lg font-bold text-cyan-400 flex items-center gap-2"},"🤖 Quản Lý & Cấu Hình AI Providers"),/*#__PURE__*/React.createElement("button",{onClick:onClose,className:"text-slate-400 hover:text-slate-200"},"✕")),msg&&/*#__PURE__*/React.createElement("div",{className:"mt-3 p-2 bg-emerald-950/60 border border-emerald-700 text-emerald-300 rounded text-xs"},msg),error&&/*#__PURE__*/React.createElement("div",{className:"mt-3 p-2 bg-red-950/60 border border-red-700 text-red-300 rounded text-xs"},error),/*#__PURE__*/React.createElement("div",{className:"mt-4 grid grid-cols-3 gap-4"},/*#__PURE__*/React.createElement("div",{className:"space-y-1.5 border-r border-[#383838] pr-3"},/*#__PURE__*/React.createElement("span",{className:"text-xs uppercase font-bold text-slate-400 block mb-2"},"Providers"),providers.map(p=>/*#__PURE__*/React.createElement("button",{key:p.id,tabIndex:0,onClick:()=>setSelectedId(p.id),onKeyDown:e=>{if(e.key===' '){e.preventDefault();updateProviderField(p.id,'is_active',!p.is_active);}},className:`w-full text-left px-3 py-2 rounded-lg text-xs font-semibold flex items-center justify-between transition ${selectedId===p.id?'bg-cyan-600 text-white shadow':'bg-[#1e1e1e] text-slate-300 hover:bg-[#2e2e2e]'}`},/*#__PURE__*/React.createElement("span",{className:"truncate"},p.name),p.is_active&&/*#__PURE__*/React.createElement("span",{className:"w-2 h-2 rounded-full bg-emerald-400"}))),/*#__PURE__*/React.createElement("div",{className:"flex gap-1 mt-2"},/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();const rearrangeNewId='provider_'+Date.now();setProviders(prev=>[...prev,{id:rearrangeNewId,name:'New Provider',provider_type:'openai_compatible',api_base_url:'https://api.openai.com/v1',api_key:'',model_name:'gpt-4o-mini',temperature:0.7,is_active:false}]);setSelectedId(rearrangeNewId);},className:"flex-1 px-2 py-1 bg-emerald-700 hover:bg-emerald-600 text-white text-xs font-bold rounded"},"+ Thêm"),providers.length>1&&/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();if(confirm(`Xóa provider "${providers.find(p=>p.id===selectedId)?.name}"?`)){setProviders(prev=>{const filtered=prev.filter(p=>p.id!==selectedId);if(filtered.length>0)setSelectedId(filtered[0].id);return filtered;});}},className:"px-2 py-1 bg-red-800 hover:bg-red-700 text-white text-xs font-bold rounded"},"Xóa"),providers.length>1&&/*#__PURE__*/React.createElement("button",{onClick:function(e){e.stopPropagation();var provs=providers.slice();var pos=-1;for(var pi=0;pi0){var tmp=provs[pos];provs[pos]=provs[pos-1];provs[pos-1]=tmp;setProviders(provs);}},className:"px-2 py-1 bg-zinc-700 hover:bg-zinc-600 text-white text-xs font-bold rounded",title:"Di chuyển lên"},"▲"),providers.length>1&&/*#__PURE__*/React.createElement("button",{onClick:function(e){e.stopPropagation();var provs=providers.slice();var pos=-1;for(var pi=0;piupdateProviderField(activeProvider.id,'name',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:border-cyan-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"API Base URL (Endpoint)"),/*#__PURE__*/React.createElement("input",{type:"text",value:activeProvider.api_base_url||'',onChange:e=>updateProviderField(activeProvider.id,'api_base_url',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs font-mono text-cyan-300 focus:outline-none focus:border-cyan-500",placeholder:"https://api.openai.com/v1"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"API Key Cá Nhân"),/*#__PURE__*/React.createElement("input",{type:"password",value:activeProvider.api_key||'',onChange:e=>updateProviderField(activeProvider.id,'api_key',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs font-mono text-slate-200 focus:outline-none focus:border-cyan-500",placeholder:"sk-..."})),/*#__PURE__*/React.createElement("div",{className:"grid grid-cols-2 gap-3"},/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"Model Name"),/*#__PURE__*/React.createElement("input",{type:"text",value:activeProvider.model_name||'',onChange:e=>updateProviderField(activeProvider.id,'model_name',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs font-mono text-amber-300 focus:outline-none focus:border-cyan-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"Temperature"),/*#__PURE__*/React.createElement("input",{type:"number",step:"0.1",min:"0",max:"2",value:activeProvider.temperature??0.7,onChange:e=>updateProviderField(activeProvider.id,'temperature',parseFloat(e.target.value)),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:border-cyan-500"}))),/*#__PURE__*/React.createElement("div",{className:"pt-2 flex items-center justify-between"},/*#__PURE__*/React.createElement("label",{className:"flex items-center gap-2 cursor-pointer text-xs text-slate-300"},/*#__PURE__*/React.createElement("input",{type:"checkbox",checked:activeProvider.is_active,onChange:e=>updateProviderField(activeProvider.id,'is_active',e.target.checked),className:"rounded accent-cyan-500"}),"Kích hoạt Provider này"),/*#__PURE__*/React.createElement("button",{type:"submit",disabled:loading,className:"px-4 py-1.5 bg-cyan-600 hover:bg-cyan-500 text-white font-semibold text-xs rounded-lg shadow transition"},loading?'Đang lưu...':'Lưu Cấu Hình AI'))))));};const PluginManagerModal=({isOpen,onClose,pluginsData})=>{if(!isOpen)return null;const[localData,setLocalData]=React.useState(pluginsData);const[sfUploadStatus,setSfUploadStatus]=React.useState('');const[sfToDelete,setSfToDelete]=React.useState(null);React.useEffect(()=>{if(isOpen){window.SonicAPI.listPlugins().then(data=>setLocalData(data)).catch(()=>setLocalData({vst_instruments:[],soundfonts:[]}));setTimeout(()=>{try{window.lucide.createIcons();}catch(e){}},50);}},[isOpen]);const handleUploadSF=async e=>{const file=e.target.files?.[0];if(!file)return;setSfUploadStatus('Uploading...');try{const result=await window.SonicAPI.uploadSoundFont(file);setSfUploadStatus('Uploaded: '+result.name);// Refresh plugin list and catalog +const GraphEditorCanvas=({buffer,zoom,timelineWidth,volumeNodes,panningNodes,fadeInLen,fadeOutLen,onUpdateNodes,graphMode})=>{const canvasRef=useRef(null);const isDraggingNode=useRef(false);const dragNodeIdx=useRef(-1);const isCreatingNode=useRef(false);const getNodes=()=>graphMode==='pan'?panningNodes:volumeNodes;const nodeLabel=n=>graphMode==='pan'?`${n.pan.toFixed(2)}`:`${n.db.toFixed(1)}dB`;const nodeY=(n,h)=>{if(graphMode==='pan')return(1-(n.pan+1)/2)*h;const zeroY=2/3*h;return n.db>=0?zeroY-n.db/3*(2/3*h):zeroY+-n.db/30*(1/3*h);};const nodeValFromY=(y,h)=>{if(graphMode==='pan')return-(y/h*2-1);const yOff=y/h;return yOff<=2/3?3*(1-yOff*3/2):-30*(yOff-2/3)*3;};useEffect(()=>{const canvas=canvasRef.current;if(!canvas||!buffer)return;const ctx=canvas.getContext('2d');const dpr=window.devicePixelRatio||1;const wrapper=canvas.parentElement?canvas.parentElement.parentElement:null;const scrollLeft=wrapper?wrapper.scrollLeft:0;const vWidth=wrapper?wrapper.clientWidth:1200;const drawWidth=Math.min(timelineWidth,Math.max(vWidth,1200));const h=canvas.parentElement?canvas.parentElement.clientHeight:200;canvas.width=Math.round(drawWidth*dpr);canvas.height=Math.round(h*dpr);ctx.scale(dpr,dpr);ctx.imageSmoothingEnabled=false;canvas.style.position='absolute';canvas.style.left=`${scrollLeft}px`;canvas.style.width=`${drawWidth}px`;canvas.style.height=`${h}px`;ctx.fillStyle='#1a1a2e';ctx.fillRect(0,0,drawWidth,h);ctx.strokeStyle='#2a2a4e';ctx.lineWidth=0.5;for(let t=0;t<=buffer.duration;t+=0.5){const x=t/buffer.duration*drawWidth;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,h);ctx.stroke();}for(let i=0;i<=10;i++){const y=i/10*h;ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(drawWidth,y);ctx.stroke();}if(fadeInLen>0){const fadeX=fadeInLen/buffer.duration*drawWidth;ctx.fillStyle='rgba(16, 185, 129, 0.12)';ctx.fillRect(0,0,fadeX,h);}if(fadeOutLen>0){const fadeX=(buffer.duration-fadeOutLen)/buffer.duration*drawWidth;const fadeW=fadeOutLen/buffer.duration*drawWidth;ctx.fillStyle='rgba(239, 68, 68, 0.12)';ctx.fillRect(fadeX,0,fadeW,h);}const nodes=getNodes();if(nodes.length>0){ctx.strokeStyle=graphMode==='pan'?'#a855f7':'#06b6d4';ctx.lineWidth=2;ctx.beginPath();nodes.forEach((n,i)=>{const x=n.time/buffer.duration*drawWidth;const y=nodeY(n,h);if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);});ctx.stroke();nodes.forEach((n,i)=>{const x=n.time/buffer.duration*drawWidth;const y=nodeY(n,h);ctx.fillStyle=graphMode==='pan'?'#a855f7':'#06b6d4';ctx.beginPath();ctx.arc(x,y,5,0,Math.PI*2);ctx.fill();ctx.fillStyle='#e4e4e7';ctx.font='9px monospace';ctx.fillText(nodeLabel(n),x+8,y+3);});}else{ctx.fillStyle='#52525b';ctx.font='11px sans-serif';ctx.textAlign='center';ctx.fillText(graphMode==='pan'?'Click to add Pan points':'Click to add Volume points',drawWidth/2,h/2);ctx.textAlign='start';}const zeroY=graphMode==='pan'?h/2:nodeY({db:0},h);ctx.strokeStyle=graphMode==='pan'?'#a855f744':'#06b6d444';ctx.lineWidth=1;ctx.setLineDash([4,4]);ctx.beginPath();ctx.moveTo(0,zeroY);ctx.lineTo(drawWidth,zeroY);ctx.stroke();ctx.setLineDash([]);},[buffer,zoom,timelineWidth,volumeNodes,panningNodes,fadeInLen,fadeOutLen,graphMode]);const handleMouseDown=e=>{const canvas=canvasRef.current;if(!canvas||!buffer)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const time=x/rect.width*buffer.duration;const val=nodeValFromY(y,rect.height);const nodes=getNodes();const snapped=Math.max(-30,Math.min(3,val));const snappedPan=Math.max(-1,Math.min(1,val));const threshold=12/rect.width*buffer.duration;const nearIdx=nodes.findIndex(n=>Math.abs(n.time-time)=0){isDraggingNode.current=true;dragNodeIdx.current=nearIdx;return;}const newNode=graphMode==='pan'?{time:+time.toFixed(3),pan:+snappedPan.toFixed(2)}:{time:+time.toFixed(3),db:+snapped.toFixed(1)};const sorted=[...nodes,newNode].sort((a,b)=>a.time-b.time);onUpdateNodes(sorted);const rearrangeNewIdx=sorted.findIndex(n=>n.time===newNode.time&&(graphMode==='pan'?n.pan:n.db)===(graphMode==='pan'?newNode.pan:newNode.db));isDraggingNode.current=true;dragNodeIdx.current=rearrangeNewIdx;isCreatingNode.current=true;};const handleMouseMove=e=>{if(!isDraggingNode.current||dragNodeIdx.current<0)return;const canvas=canvasRef.current;if(!canvas)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const time=Math.max(0,Math.min(buffer.duration,x/rect.width*buffer.duration));const val=nodeValFromY(y,rect.height);const nodes=[...getNodes()];nodes[dragNodeIdx.current]=graphMode==='pan'?{time:+time.toFixed(3),pan:+Math.max(-1,Math.min(1,val)).toFixed(2)}:{time:+time.toFixed(3),db:+Math.max(-30,Math.min(3,val)).toFixed(1)};onUpdateNodes(nodes.sort((a,b)=>a.time-b.time));};const handleMouseUp=()=>{isDraggingNode.current=false;dragNodeIdx.current=-1;isCreatingNode.current=false;};const handleContextMenu=e=>{e.preventDefault();const canvas=canvasRef.current;if(!canvas||!buffer)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const time=x/rect.width*buffer.duration;const threshold=12/rect.width*buffer.duration;const nodes=getNodes();const nearIdx=nodes.findIndex(n=>Math.abs(n.time-time)=0)onUpdateNodes(nodes.filter((_,i)=>i!==nearIdx));};return/*#__PURE__*/React.createElement("div",{style:{width:`${timelineWidth}px`,height:'100%',position:'relative',overflow:'hidden'}},/*#__PURE__*/React.createElement("canvas",{ref:canvasRef,style:{position:'absolute',top:0,left:0,imageRendering:'pixelated'},className:"cursor-crosshair rounded border border-zinc-700",onMouseDown:handleMouseDown,onMouseMove:handleMouseMove,onMouseUp:handleMouseUp,onMouseLeave:handleMouseUp,onContextMenu:handleContextMenu}));};const AuthModal=({isOpen,mode,forceMandatory,onClose,onSuccess})=>{if(!isOpen)return null;const[activeTab,setActiveTab]=useState(mode||'login');const[username,setUsername]=useState('admin');const[email,setEmail]=useState('');const[password,setPassword]=useState('');const[oldPassword,setOldPassword]=useState('');const[newPassword,setNewPassword]=useState('');const[error,setError]=useState('');const[loading,setLoading]=useState(false);const[firstTime,setFirstTime]=useState(true);useEffect(()=>{if(mode)setActiveTab(mode);if(mode==='force_change'&&!oldPassword){setOldPassword('admin123');}},[mode]);// Lần đăng nhập ĐẦU (admin còn mật khẩu mặc định) → hiện gợi ý +// username/mật khẩu; sau khi đã đổi → ẩn vĩnh viễn. +useEffect(()=>{if(!isOpen)return;if(window.SonicAPI&&window.SonicAPI.apiRequest){window.SonicAPI.apiRequest('/api/v1/auth/first-time',{method:'GET'}).then(function(d){setFirstTime(!!(d&&d.first_time));})// Fail-closed: endpoint lỗi/404 (backend chưa restart) → ẨN gợi ý +// (không hiện — user đã yêu cầu bỏ gợi ý sau lần đầu). +.catch(function(){setFirstTime(false);});}else{setFirstTime(false);}},[isOpen]);const handleSubmit=async e=>{e.preventDefault();setError('');setLoading(true);try{if(activeTab==='login'){const targetUsername=username.trim()||'admin';const targetPwd=password.trim()||'admin123';const res=await window.SonicAPI.login(targetUsername,targetPwd);localStorage.setItem('sonic_token',res.access_token);localStorage.setItem('sonic_user',JSON.stringify(res.user));if(res.user&&res.user.must_change_password){setOldPassword(targetPwd);}onSuccess(res.user,res.access_token);}else if(activeTab==='register'){const res=await window.SonicAPI.register(username.trim(),email.trim(),password.trim());localStorage.setItem('sonic_token',res.access_token);localStorage.setItem('sonic_user',JSON.stringify(res.user));onSuccess(res.user,res.access_token);}else if(activeTab==='force_change'){const res=await window.SonicAPI.changePassword(oldPassword.trim(),newPassword.trim());localStorage.setItem('sonic_token',res.access_token);const user=JSON.parse(localStorage.getItem('sonic_user')||'{}');user.must_change_password=false;localStorage.setItem('sonic_user',JSON.stringify(user));onSuccess(user,res.access_token);}}catch(err){setError(err.message||(activeTab==='login'?'Tài khoản hoặc mật khẩu không chính xác. (Nếu bạn đã đổi mật khẩu trước đó, vui lòng nhập mật khẩu mới mà bạn đã tạo)':'Thao tác không thành công'));}finally{setLoading(false);}};const isForceMode=activeTab==='force_change';const canClose=!forceMandatory&&!isForceMode;return/*#__PURE__*/React.createElement("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md"},/*#__PURE__*/React.createElement("div",{className:"bg-[#262626] border border-[#383838] rounded-xl shadow-2xl w-full max-w-md p-6 text-slate-200"},/*#__PURE__*/React.createElement("div",{className:"flex justify-between items-center pb-4 border-b border-[#383838]"},/*#__PURE__*/React.createElement("h3",{className:"text-lg font-bold text-teal-400"},isForceMode?'⚠️ Bắt Buộc Đổi Mật Khẩu Khởi Tạo':activeTab==='login'?'🔐 Đăng Nhập Hệ Thống':'📝 Đăng Ký Tài Khoản'),canClose&&/*#__PURE__*/React.createElement("button",{onClick:onClose,className:"text-slate-400 hover:text-slate-200"},"✕")),error&&/*#__PURE__*/React.createElement("div",{className:"mt-4 p-3 bg-red-900/40 border border-red-700 rounded-lg text-red-200 text-sm"},error),/*#__PURE__*/React.createElement("form",{onSubmit:handleSubmit,className:"mt-4 space-y-4"},isForceMode?/*#__PURE__*/React.createElement(React.Fragment,null,/*#__PURE__*/React.createElement("p",{className:"text-xs text-amber-400 bg-amber-950/60 p-2.5 border border-amber-800/80 rounded leading-relaxed"},"🔒 Tài khoản của bạn đang dùng mật khẩu khởi tạo mặc định. Để bảo mật hệ thống, bạn phải đổi mật khẩu mới trước khi tiếp tục."),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Mật khẩu hiện tại (Mặc định: admin123)"),/*#__PURE__*/React.createElement("input",{type:"password",autoComplete:"current-password",required:true,value:oldPassword,onChange:e=>setOldPassword(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Mật khẩu mới"),/*#__PURE__*/React.createElement("input",{type:"password",autoComplete:"new-password",required:true,value:newPassword,onChange:e=>setNewPassword(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"}))):/*#__PURE__*/React.createElement(React.Fragment,null,activeTab==='login'?/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Tên đăng nhập ",firstTime&&/*#__PURE__*/React.createElement("span",{className:"text-teal-400 font-normal"},"(Tùy chọn - Admin có thể bỏ trống)")),/*#__PURE__*/React.createElement("input",{type:"text",placeholder:"Mặc định: admin",value:username,onChange:e=>setUsername(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})):/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Tên đăng nhập"),/*#__PURE__*/React.createElement("input",{type:"text",required:true,value:username,onChange:e=>setUsername(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})),activeTab==='register'&&/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Email"),/*#__PURE__*/React.createElement("input",{type:"email",required:true,value:email,onChange:e=>setEmail(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold mb-1 text-slate-400"},"Mật khẩu ",activeTab==='login'&&firstTime&&/*#__PURE__*/React.createElement("span",{className:"text-amber-400 font-normal"},"(Lần đầu: admin123)")),/*#__PURE__*/React.createElement("input",{type:"password",autoComplete:activeTab==='login'?'current-password':'new-password',required:true,value:password,onChange:e=>setPassword(e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-2 text-sm focus:outline-none focus:border-teal-500"}))),/*#__PURE__*/React.createElement("button",{type:"submit",disabled:loading,className:"w-full py-2 bg-teal-600 hover:bg-teal-500 text-white font-semibold rounded-lg shadow transition duration-150"},loading?'Đang xác thực...':isForceMode?'Đổi Mật Khẩu Ngay':activeTab==='login'?'Đăng Nhập System':'Tạo Tài Khoản Mới'),activeTab==='login'&&!isForceMode&&firstTime&&/*#__PURE__*/React.createElement("button",{type:"button",onClick:()=>{setUsername('admin');setPassword('admin123');setError('');},className:"w-full mt-2 py-1.5 bg-amber-950/60 hover:bg-amber-900/80 text-amber-300 border border-amber-800/60 text-xs font-semibold rounded-lg transition flex items-center justify-center gap-1.5"},"🔑 Điền Nhanh Tài Khoản Admin (admin / admin123)")),!isForceMode&&/*#__PURE__*/React.createElement("div",{className:"mt-4 pt-4 border-t border-[#383838] text-center text-xs text-slate-400"},activeTab==='login'?/*#__PURE__*/React.createElement("span",null,"Chưa có tài khoản? ",/*#__PURE__*/React.createElement("button",{onClick:()=>setActiveTab('register'),className:"text-teal-400 hover:underline"},"Đăng ký ngay")):/*#__PURE__*/React.createElement("span",null,"Đã có tài khoản? ",/*#__PURE__*/React.createElement("button",{onClick:()=>setActiveTab('login'),className:"text-teal-400 hover:underline"},"Đăng nhập")))));};const AIConfigModal=({isOpen,onClose,onConfigSaved})=>{if(!isOpen)return null;const defaultProvidersList=[{id:'openai_default',name:'OpenAI Official',provider_type:'openai',api_base_url:'https://api.openai.com/v1',api_key:'',model_name:'gpt-4o',temperature:0.7,is_active:true},{id:'openai_compat_default',name:'OpenAI Compatible (Ollama/LocalAI/DeepSeek)',provider_type:'openai_compatible',api_base_url:'http://localhost:11434/v1',api_key:'ollama',model_name:'deepseek-r1',temperature:0.7,is_active:false},{id:'anthropic_default',name:'Anthropic Claude',provider_type:'anthropic',api_base_url:'https://api.anthropic.com/v1',api_key:'',model_name:'claude-3-5-sonnet',temperature:0.7,is_active:false},{id:'gemini_default',name:'Google Gemini',provider_type:'gemini',api_base_url:'https://generativelanguage.googleapis.com',api_key:'',model_name:'gemini-1.5-pro',temperature:0.7,is_active:false}];const[providers,setProviders]=useState(defaultProvidersList);const[selectedId,setSelectedId]=useState('openai_default');const[msg,setMsg]=useState('');const[error,setError]=useState('');const[loading,setLoading]=useState(false);useEffect(()=>{if(isOpen)loadConfigs();},[isOpen]);const loadConfigs=async()=>{setLoading(true);setError('');try{const data=await window.SonicAPI.getAIConfigs();if(data&&data.providers){setProviders(data.providers);if(data.providers.length>0)setSelectedId(data.providers[0].id);}}catch(err){setError(err.message||'Lỗi nạp cấu hình AI');}finally{setLoading(false);}};const handleSave=async e=>{e.preventDefault();setMsg('');setError('');setLoading(true);try{const res=await window.SonicAPI.saveAIConfigs(providers);setMsg(res.message||'Đã lưu cấu hình AI Providers thành công!');if(onConfigSaved)onConfigSaved(providers);}catch(err){setError(err.message||'Lỗi khi lưu cấu hình AI');}finally{setLoading(false);}};const updateProviderField=(id,field,value)=>{setProviders(prev=>prev.map(p=>p.id===id?{...p,[field]:value}:p));};const activeProvider=providers.find(p=>p.id===selectedId)||providers[0];return/*#__PURE__*/React.createElement("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm select-none"},/*#__PURE__*/React.createElement("div",{className:"bg-[#262626] border border-[#383838] rounded-xl shadow-2xl w-full max-w-2xl p-6 text-slate-200"},/*#__PURE__*/React.createElement("div",{className:"flex justify-between items-center pb-4 border-b border-[#383838]"},/*#__PURE__*/React.createElement("h3",{className:"text-lg font-bold text-cyan-400 flex items-center gap-2"},"🤖 Quản Lý & Cấu Hình AI Providers"),/*#__PURE__*/React.createElement("button",{onClick:onClose,className:"text-slate-400 hover:text-slate-200"},"✕")),msg&&/*#__PURE__*/React.createElement("div",{className:"mt-3 p-2 bg-emerald-950/60 border border-emerald-700 text-emerald-300 rounded text-xs"},msg),error&&/*#__PURE__*/React.createElement("div",{className:"mt-3 p-2 bg-red-950/60 border border-red-700 text-red-300 rounded text-xs"},error),/*#__PURE__*/React.createElement("div",{className:"mt-4 grid grid-cols-3 gap-4"},/*#__PURE__*/React.createElement("div",{className:"space-y-1.5 border-r border-[#383838] pr-3"},/*#__PURE__*/React.createElement("span",{className:"text-xs uppercase font-bold text-slate-400 block mb-2"},"Providers"),providers.map(p=>/*#__PURE__*/React.createElement("button",{key:p.id,tabIndex:0,onClick:()=>setSelectedId(p.id),onKeyDown:e=>{if(e.key===' '){e.preventDefault();updateProviderField(p.id,'is_active',!p.is_active);}},className:`w-full text-left px-3 py-2 rounded-lg text-xs font-semibold flex items-center justify-between transition ${selectedId===p.id?'bg-cyan-600 text-white shadow':'bg-[#1e1e1e] text-slate-300 hover:bg-[#2e2e2e]'}`},/*#__PURE__*/React.createElement("span",{className:"truncate"},p.name),p.is_active&&/*#__PURE__*/React.createElement("span",{className:"w-2 h-2 rounded-full bg-emerald-400"}))),/*#__PURE__*/React.createElement("div",{className:"flex gap-1 mt-2"},/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();const rearrangeNewId='provider_'+Date.now();setProviders(prev=>[...prev,{id:rearrangeNewId,name:'New Provider',provider_type:'openai_compatible',api_base_url:'https://api.openai.com/v1',api_key:'',model_name:'gpt-4o-mini',temperature:0.7,is_active:false}]);setSelectedId(rearrangeNewId);},className:"flex-1 px-2 py-1 bg-emerald-700 hover:bg-emerald-600 text-white text-xs font-bold rounded"},"+ Thêm"),providers.length>1&&/*#__PURE__*/React.createElement("button",{onClick:e=>{e.stopPropagation();if(confirm(`Xóa provider "${providers.find(p=>p.id===selectedId)?.name}"?`)){setProviders(prev=>{const filtered=prev.filter(p=>p.id!==selectedId);if(filtered.length>0)setSelectedId(filtered[0].id);return filtered;});}},className:"px-2 py-1 bg-red-800 hover:bg-red-700 text-white text-xs font-bold rounded"},"Xóa"),providers.length>1&&/*#__PURE__*/React.createElement("button",{onClick:function(e){e.stopPropagation();var provs=providers.slice();var pos=-1;for(var pi=0;pi0){var tmp=provs[pos];provs[pos]=provs[pos-1];provs[pos-1]=tmp;setProviders(provs);}},className:"px-2 py-1 bg-zinc-700 hover:bg-zinc-600 text-white text-xs font-bold rounded",title:"Di chuyển lên"},"▲"),providers.length>1&&/*#__PURE__*/React.createElement("button",{onClick:function(e){e.stopPropagation();var provs=providers.slice();var pos=-1;for(var pi=0;piupdateProviderField(activeProvider.id,'name',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:border-cyan-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"API Base URL (Endpoint)"),/*#__PURE__*/React.createElement("input",{type:"text",value:activeProvider.api_base_url||'',onChange:e=>updateProviderField(activeProvider.id,'api_base_url',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs font-mono text-cyan-300 focus:outline-none focus:border-cyan-500",placeholder:"https://api.openai.com/v1"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"API Key Cá Nhân"),/*#__PURE__*/React.createElement("input",{type:"password",value:activeProvider.api_key||'',onChange:e=>updateProviderField(activeProvider.id,'api_key',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs font-mono text-slate-200 focus:outline-none focus:border-cyan-500",placeholder:"sk-..."})),/*#__PURE__*/React.createElement("div",{className:"grid grid-cols-2 gap-3"},/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"Model Name"),/*#__PURE__*/React.createElement("input",{type:"text",value:activeProvider.model_name||'',onChange:e=>updateProviderField(activeProvider.id,'model_name',e.target.value),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs font-mono text-amber-300 focus:outline-none focus:border-cyan-500"})),/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement("label",{className:"block text-xs font-semibold text-slate-400 mb-1"},"Temperature"),/*#__PURE__*/React.createElement("input",{type:"number",step:"0.1",min:"0",max:"2",value:activeProvider.temperature??0.7,onChange:e=>updateProviderField(activeProvider.id,'temperature',parseFloat(e.target.value)),className:"w-full bg-[#1e1e1e] border border-[#383838] rounded px-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:border-cyan-500"}))),/*#__PURE__*/React.createElement("div",{className:"pt-2 flex items-center justify-between"},/*#__PURE__*/React.createElement("label",{className:"flex items-center gap-2 cursor-pointer text-xs text-slate-300"},/*#__PURE__*/React.createElement("input",{type:"checkbox",checked:activeProvider.is_active,onChange:e=>updateProviderField(activeProvider.id,'is_active',e.target.checked),className:"rounded accent-cyan-500"}),"Kích hoạt Provider này"),/*#__PURE__*/React.createElement("button",{type:"submit",disabled:loading,className:"px-4 py-1.5 bg-cyan-600 hover:bg-cyan-500 text-white font-semibold text-xs rounded-lg shadow transition"},loading?'Đang lưu...':'Lưu Cấu Hình AI'))))));};const PluginManagerModal=({isOpen,onClose,pluginsData})=>{if(!isOpen)return null;const[localData,setLocalData]=React.useState(pluginsData);const[sfUploadStatus,setSfUploadStatus]=React.useState('');const[sfToDelete,setSfToDelete]=React.useState(null);React.useEffect(()=>{if(isOpen){window.SonicAPI.listPlugins().then(data=>setLocalData(data)).catch(()=>setLocalData({vst_instruments:[],soundfonts:[]}));setTimeout(()=>{try{window.lucide.createIcons();}catch(e){}},50);}},[isOpen]);const handleUploadSF=async e=>{const file=e.target.files?.[0];if(!file)return;setSfUploadStatus('Uploading...');try{const result=await window.SonicAPI.uploadSoundFont(file);setSfUploadStatus('Uploaded: '+result.name);// Refresh plugin list and catalog const data=await window.SonicAPI.listPlugins();setLocalData(data);try{const cat=await window.SonicAPI.getSoundfontCatalog();window.__soundfontCatalog=cat;}catch(_){}}catch(err){setSfUploadStatus('Error: '+err.message);}};const[pmTab,setPmTab]=React.useState('soundfont');return React.createElement('div',{className:'fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm',onClick:onClose},React.createElement('div',{className:'bg-[#1e1e1e] border border-[#383838] rounded-xl shadow-2xl w-full max-w-3xl p-0 text-slate-200 overflow-hidden flex flex-col',style:{maxHeight:'80vh'},onClick:e=>e.stopPropagation()},// Header React.createElement('div',{className:'flex items-center justify-between px-5 py-3 bg-[#252525] border-b border-[#383838]'},React.createElement('h3',{className:'text-base font-bold text-cyan-400 flex items-center gap-2'},React.createElement('i',{'data-lucide':'zap',className:'w-4 h-4'}),'Plugin Manager (SoundFont / VSTi)'),React.createElement('button',{onClick:onClose,className:'text-zinc-500 hover:text-zinc-200 transition'},React.createElement('i',{'data-lucide':'x',className:'w-4 h-4'}))),// Left-right body React.createElement('div',{className:'flex flex-1 overflow-hidden',style:{minHeight:'300px'}},// Left sidebar diff --git a/app/templates/index.html b/app/templates/index.html index 6b416a7..7c9189f 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -24,7 +24,7 @@ - +