// ==========================================
// AIPanel Component
// ==========================================

const AIPanel = ({
    isOpen,
    onToggle,
    lang,
    t,
    // Template & Style
    selectedTemplate,
    onTemplateSwitch,
    currentStyle,
    setCurrentStyle,
    // Image Config
    aspectRatio,
    setAspectRatio,
    imageQuality,
    setImageQuality,
    // Grid config
    gridCols,
    gridRows,
    cellWidth,
    cellHeight,
    onGridColsChange,
    onGridRowsChange,
    setCellWidth,
    setCellHeight,
    // Calculated dimensions
    totalWidth,
    totalHeight,
    // Auto calc toggle
    autoCalcCellSize,
    setAutoCalcCellSize,
    // Row steps
    rowSteps,
    setRowSteps,
    onAddRow,
    onDeleteRow,
    // Colors
    bgColor,
    setBgColor,
    // Character
    charStyle,
    setCharStyle,
    extraSpecs,
    setExtraSpecs,
    // Reference image
    refPreview,
    onRefUpload,
    // Prompt
    finalPrompt,
    setFinalPrompt,
    onResetPrompt,
    onCopyPrompt,
    copyButtonText,
    // Generate
    genState,
    onGenerate
}) => {
    const { SparklesIcon, ChevronIcon } = window.Icons;

    return (
        <section className="bg-slate-900/40 rounded-3xl border border-slate-800 overflow-hidden shadow-2xl transition-all duration-500">
            <div onClick={onToggle} className="p-6 flex items-center justify-between cursor-pointer hover:bg-slate-800/40 transition-colors">
                <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-400">
                        <SparklesIcon />
                    </div>
                    <div>
                        <h2 className="font-bold text-xl">{t('Generation Config', '生成配置')}</h2>
                        <p className="text-xs text-slate-500">{t('Procedural generation based on strict grid constraints.', '基于严格网格约束的程序化生成。')}</p>
                    </div>
                </div>
                <ChevronIcon open={isOpen} />
            </div>

            <div className={`transition-all duration-500 overflow-hidden ${isOpen ? 'max-h-[4000px] opacity-100' : 'max-h-0 opacity-0'}`}>
                <div className="p-4 border-t border-slate-800 grid grid-cols-1 xl:grid-cols-12 gap-4">
                    {/* Column 1 - Settings & Row Instructions */}
                    <div className="xl:col-span-3 space-y-3">
                        {/* Row 1: Presets + Dropdowns */}
                        <div className="grid grid-cols-2 gap-3">
                            {/* Action Presets */}
                            <div>
                                <label className="text-[8px] font-black uppercase text-slate-500 tracking-widest px-1 mb-1 block">{t('Presets', '预设')}</label>
                                <div className="grid grid-cols-2 gap-1">
                                    {window.ANIMATION_TEMPLATES.map(tpl => (
                                        <button key={tpl.id} onClick={() => onTemplateSwitch(tpl)} className={`flex flex-col items-center gap-0.5 p-1.5 rounded-lg border transition-all ${selectedTemplate.id === tpl.id ? 'bg-indigo-600/10 border-indigo-500 text-indigo-400' : 'bg-slate-950 border-slate-800 text-slate-500 hover:border-slate-700'}`}>
                                            <span className="text-sm">{tpl.icon}</span>
                                            <span className="text-[7px] font-bold uppercase">{lang === 'en' ? tpl.name.en : tpl.name.cn}</span>
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Style/Ratio/Quality */}
                            <div className="space-y-1">
                                <div className="grid grid-cols-3 gap-1">
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Style', '画风')}</label>
                                        <select value={currentStyle.id} onChange={e => { const style = window.ART_STYLES.find(s => s.id === e.target.value); if (style) setCurrentStyle(style); }} className="w-full bg-slate-950 border border-slate-800 rounded px-1 py-1 text-[10px] cursor-pointer outline-none">
                                            {window.ART_STYLES.map(style => (<option key={style.id} value={style.id}>{lang === 'en' ? style.name.en : style.name.cn}</option>))}
                                        </select>
                                    </div>
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Ratio', '比例')}</label>
                                        <select value={aspectRatio} onChange={e => setAspectRatio(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded px-1 py-1 text-[10px] cursor-pointer outline-none">
                                            {window.GeminiApi.ASPECT_RATIOS.map(ratio => (<option key={ratio.id} value={ratio.id}>{ratio.label}</option>))}
                                        </select>
                                    </div>
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Qual', '画质')}</label>
                                        <select value={imageQuality} onChange={e => setImageQuality(e.target.value)} className="w-full bg-slate-950 border border-slate-800 rounded px-1 py-1 text-[10px] cursor-pointer outline-none">
                                            {window.GeminiApi.IMAGE_QUALITIES.map(qual => (<option key={qual.id} value={qual.id}>{qual.label}</option>))}
                                        </select>
                                    </div>
                                </div>
                                {/* Grid Config */}
                                <div className="grid grid-cols-4 gap-1">
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Col', '列')}</label>
                                        <input type="number" value={gridCols} onChange={onGridColsChange} className="w-full bg-slate-950 border border-slate-800 rounded px-1 py-1 text-[10px] outline-none" />
                                    </div>
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Row', '行')}</label>
                                        <input type="number" value={gridRows} onChange={onGridRowsChange} className="w-full bg-slate-950 border border-slate-800 rounded px-1 py-1 text-[10px] outline-none" />
                                    </div>
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('W', '宽')}</label>
                                        <input type="number" value={cellWidth} onChange={e => { setAutoCalcCellSize(false); setCellWidth(e.target.value === '' ? '' : parseInt(e.target.value)); }} onBlur={() => setCellWidth(Math.max(8, Number(cellWidth) || 8))} className={`w-full bg-slate-950 border rounded px-1 py-1 text-[10px] outline-none ${autoCalcCellSize ? 'border-indigo-500/30 text-indigo-300' : 'border-slate-800'}`} />
                                    </div>
                                    <div>
                                        <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('H', '高')}</label>
                                        <input type="number" value={cellHeight} onChange={e => { setAutoCalcCellSize(false); setCellHeight(e.target.value === '' ? '' : parseInt(e.target.value)); }} onBlur={() => setCellHeight(Math.max(8, Number(cellHeight) || 8))} className={`w-full bg-slate-950 border rounded px-1 py-1 text-[10px] outline-none ${autoCalcCellSize ? 'border-indigo-500/30 text-indigo-300' : 'border-slate-800'}`} />
                                    </div>
                                </div>
                                <div className="flex items-center justify-between px-0.5">
                                    <span className="text-[8px] text-indigo-400 font-mono">{totalWidth}×{totalHeight}</span>
                                    <div className="flex items-center gap-1">
                                        <span className="text-[7px] text-slate-600">{t('Auto', '自动')}</span>
                                        <button onClick={() => setAutoCalcCellSize(!autoCalcCellSize)} className={`w-6 h-3 rounded-full transition-all ${autoCalcCellSize ? 'bg-indigo-500' : 'bg-slate-700'}`}>
                                            <div className={`w-2 h-2 rounded-full bg-white transition-transform ${autoCalcCellSize ? 'translate-x-3' : 'translate-x-0.5'}`} />
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Background Color + Reference */}
                        <div className="flex gap-2 items-center">
                            <input type="color" value={bgColor} onChange={(e) => setBgColor(e.target.value)} className="w-6 h-6 rounded bg-transparent border border-slate-800 cursor-pointer shrink-0" />
                            <input type="text" value={bgColor} onChange={(e) => setBgColor(e.target.value)} className="w-16 bg-slate-950 border border-slate-800 rounded px-1 py-1 text-[9px] font-mono text-slate-300" />
                            <button onClick={() => setBgColor('#ffffff')} className="w-5 h-5 bg-white border border-slate-700 rounded" title="White"></button>
                            <button onClick={() => setBgColor('#000000')} className="w-5 h-5 bg-black border border-slate-700 rounded" title="Black"></button>
                            <button onClick={() => setBgColor('#00ff00')} className="w-5 h-5 bg-[#00ff00] border border-slate-700 rounded" title="Green"></button>
                            <div className="ml-auto relative w-8 h-8 rounded border-2 border-dashed border-slate-700 hover:border-indigo-500 transition-colors flex items-center justify-center overflow-hidden shrink-0 cursor-pointer">
                                <input type="file" onChange={onRefUpload} className="absolute inset-0 opacity-0 cursor-pointer z-10" />
                                {refPreview ? <img src={refPreview} className="w-full h-full object-cover" alt="Ref" /> : <span className="text-[10px] text-slate-600">+</span>}
                            </div>
                        </div>

                        {/* Row Instructions */}
                        <div className="bg-slate-950 rounded-lg border border-slate-800 overflow-hidden">
                            <div className="flex justify-between items-center px-2 py-1 bg-slate-900 border-b border-slate-800">
                                <label className="text-[7px] font-black text-slate-500 uppercase tracking-widest">{t('Row Instructions', '分行指令')}</label>
                            </div>
                            <div className="max-h-28 overflow-y-auto">
                                {rowSteps.map((step, idx) => (
                                    <div key={idx} className="flex items-center gap-1 px-2 py-1 border-b border-slate-800/50 last:border-0">
                                        <input type="text" value={step.label} onChange={(e) => { const n = [...rowSteps]; n[idx].label = e.target.value; setRowSteps(n); }} className="w-8 bg-transparent text-indigo-400 text-[9px] font-mono font-bold text-center outline-none" />
                                        <input type="text" value={step.action} onChange={e => { const n = [...rowSteps]; n[idx].action = e.target.value; setRowSteps(n); }} className="flex-1 bg-transparent text-[9px] text-slate-300 outline-none" placeholder={t('Action...', '动作...')} />
                                        {rowSteps.length > 1 && <button onClick={() => onDeleteRow(idx)} className="text-slate-600 hover:text-rose-500 text-[10px]">✕</button>}
                                    </div>
                                ))}
                            </div>
                            <button onClick={onAddRow} className="w-full py-1 bg-slate-900/50 hover:bg-slate-800 text-slate-500 hover:text-indigo-400 text-[7px] font-bold uppercase transition-colors border-t border-slate-800">+ {t('Add', '添加')}</button>
                        </div>

                        {/* Character & Details */}
                        <div className="grid grid-cols-2 gap-2">
                            <div>
                                <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Character', '角色')}</label>
                                <textarea value={charStyle} onChange={e => setCharStyle(e.target.value)} placeholder={t('Armor...', '盔甲...')} className="w-full h-12 bg-slate-950 border border-slate-800 rounded p-1.5 text-[9px] outline-none resize-none" />
                            </div>
                            <div>
                                <label className="text-[7px] font-bold text-slate-500 uppercase px-0.5 block">{t('Details', '细节')}</label>
                                <textarea value={extraSpecs} onChange={e => setExtraSpecs(e.target.value)} placeholder={t('Magic...', '魔法...')} className="w-full h-12 bg-slate-950 border border-slate-800 rounded p-1.5 text-[9px] outline-none resize-none" />
                            </div>
                        </div>
                    </div>

                    {/* Column 2 - Prompt */}
                    <div className="xl:col-span-4 flex flex-col gap-3">
                        <div className="flex-1 flex flex-col">
                            <div className="flex items-center justify-between px-1 mb-1">
                                <label className="text-[8px] font-bold text-slate-500 uppercase">{t('Final Prompt', '最终提示词')}</label>
                                <div className="flex gap-2">
                                    <button onClick={onResetPrompt} className="text-[8px] font-bold uppercase text-slate-500 hover:text-amber-400 transition-colors">{t('Reset', '重置')}</button>
                                    <button onClick={onCopyPrompt} className="text-[8px] font-bold uppercase text-slate-500 hover:text-indigo-400 transition-colors">{copyButtonText}</button>
                                </div>
                            </div>
                            <textarea value={finalPrompt} onChange={e => setFinalPrompt(e.target.value)} className="flex-1 min-h-[380px] bg-slate-950 border border-slate-800 rounded-xl p-3 text-[10px] font-mono text-slate-300 outline-none resize-none" placeholder={t('Edit prompt...', '编辑提示词...')} />
                        </div>

                        {/* Generate Button */}
                        <button onClick={onGenerate} disabled={genState.isLoading} className="w-full py-3 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-black text-sm uppercase tracking-widest transition-all shadow-xl shadow-indigo-600/20 active:scale-95 disabled:opacity-50 flex items-center justify-center gap-3">
                            {genState.isLoading ? <><div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin" />{t('Processing...', '生成中...')} </> : t('Generate', '开始生成')}
                        </button>
                    </div>

                    {/* Column 3 - Preview Area */}
                    <div className="xl:col-span-5 bg-slate-950 rounded-2xl border border-slate-800 flex items-center justify-center relative min-h-[480px] group overflow-hidden">
                        {genState.generatedImageBase64 ? (
                            <img
                                src={genState.generatedImageBase64}
                                className="max-w-full max-h-[850px] object-contain transition-transform duration-700 group-hover:scale-105"
                                style={{ imageRendering: 'pixelated' }}
                                alt="Generated Sprite Sheet"
                            />
                        ) : (
                            <div className="text-center opacity-10 space-y-4">
                                <div className="w-24 h-24 rounded-3xl bg-slate-800 mx-auto animate-pulse" />
                                <p className="text-[11px] font-black uppercase tracking-[0.5em]">{t('Viewport Offline', '视图等待中')}</p>
                            </div>
                        )}
                        {genState.isLoading && (
                            <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm flex items-center justify-center">
                                <div className="w-8 h-8 border-4 border-indigo-500/20 border-t-indigo-500 rounded-full animate-spin" />
                            </div>
                        )}
                        {genState.error && (
                            <div className="absolute bottom-6 left-6 right-6 p-4 bg-rose-500/10 border border-rose-500/20 text-rose-400 text-[10px] font-bold rounded-xl">
                                {genState.error}
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </section>
    );
};

window.AIPanel = AIPanel;
