import re

with open("resources/js/components/AdminDashboard.tsx", "r", encoding="utf-8") as f:
    lines = f.readlines()

def get_block(start_str, end_strs):
    start_idx = -1
    for i, l in enumerate(lines):
        if start_str in l:
            start_idx = i
            break
    if start_idx == -1: return [], -1, -1
    
    end_idx = -1
    for i in range(start_idx+1, len(lines)):
        for e in end_strs:
            if e in lines[i]:
                end_idx = i
                return lines[start_idx:end_idx], start_idx, end_idx
    return [], -1, -1

a_block, a_s, a_e = get_block("              {activeTab === 'appearance' && canAccess('appearance') && (", ["              {activeTab === 'categories' && canAccess('products') && ("])

if a_block:
    a_content = "import React, { useState, useEffect } from 'react';\n"
    a_content += "import { Palette, Globe, Type, LayoutTemplate, RefreshCw, CheckCircle, ImageIcon, Search, Upload } from 'lucide-react';\n\n"
    a_content += "const Input = ({ label, value, onChange, placeholder, icon, type = 'text', readOnly }: any) => (\n"
    a_content += "  <div>\n"
    a_content += "    <label className=\"text-[10px] font-black uppercase tracking-widest text-slate-500 dark:text-slate-400 mb-2 block\">{label}</label>\n"
    a_content += "    <div className=\"relative\">\n"
    a_content += "      {icon && <div className=\"absolute left-4 top-1/2 -translate-y-1/2\">{icon}</div>}\n"
    a_content += "      <input type={type} value={value || ''} onChange={e => onChange(e.target.value)} readOnly={readOnly} placeholder={placeholder} className={`w-full h-12 bg-slate-50 dark:bg-slate-800 rounded-xl outline-none font-medium text-sm text-slate-800 dark:text-slate-200 border border-slate-200 dark:border-slate-700 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 transition-all ${icon ? 'pl-11 pr-4' : 'px-4'}`} />\n"
    a_content += "    </div>\n"
    a_content += "  </div>\n"
    a_content += ");\n\n"
    a_content += "interface AppearanceManagerProps {\n"
    a_content += "  settings: any;\n"
    a_content += "  saveSiteSettings: (updates: any) => Promise<void>;\n"
    a_content += "  isSaving: boolean;\n"
    a_content += "  canAccess: (section: string, action?: string) => boolean;\n"
    a_content += "  uploadImageToPHP: (file: File) => Promise<string>;\n"
    a_content += "}\n\n"
    a_content += "export default function AppearanceManager({ settings, saveSiteSettings, isSaving, canAccess, uploadImageToPHP }: AppearanceManagerProps) {\n"
    a_content += "  const [brandingForm, setBrandingForm] = useState({ siteName: '', tabTitle: '' });\n\n"
    a_content += "  useEffect(() => {\n"
    a_content += "    setBrandingForm({ siteName: settings?.siteName || '', tabTitle: settings?.tabTitle || '' });\n"
    a_content += "  }, [settings]);\n\n"
    a_content += "  return (\n    <>\n"
    
    clean_a = "".join(a_block).replace("              {activeTab === 'appearance' && canAccess('appearance') && (", "").rstrip()
    if clean_a.endswith(")}"):
        clean_a = clean_a[:-2]
        
    a_content += clean_a + "\n    </>\n  );\n}\n"
    
    with open("resources/js/components/admin/AppearanceManager.tsx", "w", encoding="utf-8") as f:
        f.write(a_content)
    print("AppearanceManager.tsx created successfully!")
    
    # Replace in AdminDashboard.tsx
    for i in range(len(lines)):
        if "              {activeTab === 'appearance' && canAccess('appearance') && (" in lines[i]:
            for j in range(a_s, a_e):
                lines[j] = ""
            lines[i] = """              {activeTab === 'appearance' && canAccess('appearance') && (
                <AppearanceManager
                  settings={settings}
                  saveSiteSettings={saveSiteSettings}
                  isSaving={isSaving}
                  canAccess={canAccess}
                  uploadImageToPHP={uploadImageToPHP}
                />
              )}\n"""
            break

# Remove brandingForm state from AdminDashboard.tsx
for i, l in enumerate(lines):
    if "const [brandingForm, setBrandingForm] = useState" in l:
        lines[i] = ""
    elif "setBrandingForm({" in l:
        # It's multi-line setBrandingForm in useEffect
        lines[i] = ""
        lines[i+1] = ""
        lines[i+2] = ""
        lines[i+3] = ""
        break

# Insert import
import_idx = -1
for i, l in enumerate(lines):
    if "import MarketingManager" in l:
        import_idx = i
        break
if import_idx != -1:
    lines.insert(import_idx+1, "import AppearanceManager from './admin/AppearanceManager';\n")

with open("resources/js/components/AdminDashboard.tsx", "w", encoding="utf-8") as f:
    f.writelines(lines)

print("AdminDashboard.tsx updated successfully!")
