import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { ApiError, baseUrl, request } from './admin/api';
import '../css/admin.css';
import {SectionEditor, type Section} from './admin/SectionEditor';
import {MediaLibrary,type Media} from './admin/MediaLibrary';
import {CategoryManager,type Category} from './admin/CategoryManager';
import {Inbox} from './admin/Inbox';
import {ContentReferences} from './admin/ContentReferences';
import {RedirectManager} from './admin/RedirectManager';
import {BodyEditor} from './admin/BodyEditor';
import {SiteSettings} from './admin/SiteSettings';
import {ContentDetails,type Details} from './admin/ContentDetails';

type Content = { id: number; type: string; locale: string; title: string; slug: string; excerpt: string|null; body: string|null; status: string; path: string; seo_title: string|null; seo_description: string|null; noindex: boolean; published_at: string|null; version: number; template: string; sections: Section[] | null; migration_source?: string | null; featured_media_id:number|null; featured_media:Media|null; categories:Category[]; category_ids?:number[]; details:Details|null; body_format?:string; display_author?:string|null; };
type Form = Omit<Content,'id'|'path'|'version'>;
type Page = {data:Content[];current_page:number;last_page:number;total:number};
const types: Record<string,string> = {project:'پروژه‌ها و نمونه‌کارها',page:'صفحات',post:'مقاله‌ها',service:'خدمات',case_study:'مطالعات موردی',resource:'منابع',faq:'سؤالات متداول',technology:'فناوری‌ها',testimonial:'نظرات مشتریان',team:'تیم',ai_solution:'راهکارهای هوش مصنوعی',kb:'پایگاه دانش',integration:'یکپارچه‌سازی‌ها'};
const statuses:Record<string,string>={draft:'پیش‌نویس',published:'منتشرشده',archived:'آرشیوشده'};
const empty:Form={type:'page',locale:'en',title:'',slug:'',excerpt:'',body:'',status:'draft',seo_title:'',seo_description:'',noindex:false,published_at:null,template:'default',sections:[],featured_media_id:null,featured_media:null,categories:[],category_ids:[],details:{}};
function App() {
 const [module,setModule]=useState<'content'|'media'|'categories'|'contacts'|'settings'|'redirects'>('content');
 const [user,setUser]=useState<{name:string;role:string}|null>(null);
 const [page,setPage]=useState<Page|null>(null), [number,setNumber]=useState(1), [type,setType]=useState(''),[query,setQuery]=useState('');
 const [loading,setLoading]=useState(true),[error,setError]=useState(''),[notice,setNotice]=useState(''),[saving,setSaving]=useState(false);
 const [editing,setEditing]=useState<Content|null|undefined>(undefined),[form,setForm]=useState<Form>(empty),[fields,setFields]=useState<Record<string,string[]>>({}),[refresh,setRefresh]=useState(0);
 useEffect(()=>{request<{data:{name:string;role:string}}>('/me').then(x=>setUser(x.data)).catch(e=>setError(e.message));},[]);
 useEffect(()=>{
  if(module!=='content')return;
  let active=true; setLoading(true); setError('');
  const timer=window.setTimeout(()=>{const params=new URLSearchParams({page:String(number),...(type?{type}:{}),...(query?{q:query}:{})});
  request<Page>(`/contents?${params}`).then(x=>{if(active)setPage(x);}).catch(e=>{if(active)setError(e.message);}).finally(()=>{if(active)setLoading(false);});},200);
  return ()=>{active=false;clearTimeout(timer);};
 },[number,type,query,refresh,module]);
 function edit(item:Content|null) { setEditing(item);setForm(item?{...item,category_ids:item.categories?.map(category=>category.id)??[]}: {...empty,type:type||'page'});setFields({});setError('');setNotice(''); }
 function field<K extends keyof Form>(key:K,value:Form[K]){setForm(prev=>({...prev,[key]:value}));}
 async function save(event:React.FormEvent){event.preventDefault();setSaving(true);setError('');setFields({});try {
  await request(editing?`/contents/${editing.id}`:'/contents',{method:editing?'PUT':'POST',body:JSON.stringify({...form,details:{...form.details,...Object.fromEntries(['features','outcomes','technologies'].filter(key=>Array.isArray(form.details?.[key as keyof Details])).map(key=>[key,(form.details?.[key as keyof Details] as string[]).map(value=>value.trim()).filter(Boolean)]))},...(editing?{version:editing.version}:{})})});
  setEditing(undefined);setNotice('محتوا ذخیره شد.');setRefresh(x=>x+1);
 } catch(e){if(e instanceof ApiError){setError(e.status===409?'نسخه جدیدتری از این محتوا ذخیره شده است. متن خود را نگه دارید و فهرست را تازه‌سازی کنید.':e.message);setFields(e.fields);}else setError('ارتباط با سرور برقرار نشد.');}finally{setSaving(false);}}
 async function logout(){try{await request('/logout',{method:'POST'});window.location.assign(`${baseUrl}/admin/login`);}catch(e){setError(e instanceof Error?e.message:'خروج انجام نشد.');}}
 function navigate(next:'content'|'media'|'categories'|'contacts'|'settings'|'redirects',contentType=''){if(editing!==undefined&&!window.confirm('تغییرات ذخیره‌نشده کنار گذاشته شوند؟'))return;setEditing(undefined);setModule(next);setType(contentType);setNumber(1);setError('');setNotice('');}
 const errors=(name:string)=>fields[name]?.map((x,i)=><small className="field-error" key={i}>{x}</small>);
 return <div className="admin-app"><aside className="admin-sidebar"><a className="admin-brand" href={`${baseUrl}/admin`}>ROCKETZI<span>مدیریت استودیو</span></a><button className={module==='content'&&!type?'active':''} onClick={()=>navigate('content')}>همه محتواها</button>{Object.entries(types).map(([key,label])=><button key={key} className={module==='content'&&type===key?'active':''} onClick={()=>navigate('content',key)}>{label}</button>)}<hr className="sidebar-divider"/><button className={module==='media'?'active':''} onClick={()=>navigate('media')}>کتابخانه رسانه</button><button className={module==='categories'?'active':''} onClick={()=>navigate('categories')}>دسته‌بندی‌ها</button><button className={module==='contacts'?'active':''} onClick={()=>navigate('contacts')}>درخواست‌های تماس</button>{user?.role==='owner'&&<button onClick={()=>navigate('redirects')}>ریدایرکت‌ها</button>}{user?.role==='owner'&&<button className={module==='settings'?'active':''} onClick={()=>navigate('settings')}>تنظیمات سایت</button>}<a href={`${baseUrl}/`} target="_blank" rel="noreferrer">مشاهده سایت ↗</a><button onClick={logout}>خروج از حساب</button></aside>
 <main className="admin-main"><header className="admin-header"><div><span className="eyebrow">CONTENT WORKSPACE</span><h1>{module==='redirects'?'ریدایرکت‌ها':module==='settings'?'تنظیمات سایت':module==='media'?'رسانه‌ها':module==='categories'?'دسته‌بندی‌ها':module==='contacts'?'درخواست‌های تماس':type?types[type]:'مدیریت محتوا'}</h1></div><span className="muted">{user?.name}</span></header>
 <div className="migration-note">نسخه مستقل در حال توسعه است. محتوای واقعی منتقل شده؛ تطبیق نهایی صفحات و امکانات اختصاصی پیش از انتشار ادامه دارد.</div>
 {error&&<div className="admin-alert error" role="alert">{error} <button onClick={()=>setRefresh(x=>x+1)}>تلاش مجدد</button></div>}{notice&&<p className="admin-alert" role="status">{notice}</p>}
 {module==='redirects'?<RedirectManager/>:module==='settings'?<SiteSettings/>:module==='media'?<MediaLibrary/>:module==='categories'?<CategoryManager types={types}/>:module==='contacts'?<Inbox/>:<>{editing!==undefined?<section className="card admin-editor"><h2>{editing?'ویرایش محتوا':'محتوای جدید'}</h2>{editing?.migration_source?.includes('preview')&&<p className="migration-note">منبع: متن پیش‌فرض فایل قالب؛ تنظیمات واقعی دیتابیس و ACF هنوز استخراج نشده‌اند.</p>}<p className="muted">متن اصلی و جزئیات محتوا را ویرایش کنید؛ برای صفحات ساختاریافته از بخش‌های صفحه استفاده کنید.</p><form onSubmit={save}>
 <div className="form-grid"><label>عنوان<input required maxLength={255} value={form.title} onChange={e=>field('title',e.target.value)}/>{errors('title')}</label><label>نامک آدرس<input required dir="ltr" disabled={!!editing} value={form.slug} onChange={e=>field('slug',e.target.value)}/>{errors('slug')}{errors('path')}</label>
 <label>نوع محتوا<select disabled={!!editing} value={form.type} onChange={e=>{field('type',e.target.value);field('category_ids',[]);field('details',{});}}>{Object.entries(types).map(([key,label])=><option value={key} key={key}>{label}</option>)}</select></label><label>زبان<select value={form.locale} onChange={e=>{field('locale',e.target.value);field('category_ids',[]);}}><option value="en">English</option><option value="fa">فارسی</option></select></label></div>
 {form.type==='page'&&<label>قالب صفحه<select value={form.template} disabled={!!editing&&['listing','contact'].includes(form.template)} onChange={e=>field('template',e.target.value)}><option value="default">صفحه ساده</option><option value="home">صفحه اصلی کلاسیک</option><option value="studio">استودیوی راکتزی — طراحی جدید</option><option value="about">درباره ما</option>{['listing','contact'].includes(form.template)&&<option value={form.template}>صفحه متصل به فهرست یا فرم</option>}</select>{errors('template')}</label>}
 <label>خلاصه<textarea rows={3} value={form.excerpt??''} onChange={e=>field('excerpt',e.target.value)}/>{errors('excerpt')}</label><BodyEditor key={editing?.id??'new'} value={form.body??''} format={form.body_format??'plain'} locale={form.locale} onChange={(body,body_format)=>setForm(prev=>({...prev,body,body_format}))}/>{errors('body')}{errors('body_format')}
 {['home','about'].includes(form.template)&&<SectionEditor sections={form.sections??[]} onChange={value=>field('sections',value)}/>}
 {Object.entries(fields).filter(([name])=>name.startsWith('sections')).map(([name,messages])=><p className="field-error" key={name}>{messages.join(' ')}</p>)}
 <ContentReferences type={form.type} locale={form.locale} categoryIds={form.category_ids??[]} onCategories={ids=>field('category_ids',ids)} media={form.featured_media} onMedia={media=>{field('featured_media',media);field('featured_media_id',media?.id??null);}}/>{errors('category_ids')}{errors('featured_media_id')}
 <ContentDetails template={form.template} type={form.type} value={form.details??{}} onChange={details=>field('details',details)}/>{Object.entries(fields).filter(([name])=>name.startsWith('details')).map(([name,messages])=><p className="field-error" key={name}>{messages.join(' ')}</p>)}
 <details><summary>تنظیمات سئو</summary><label>عنوان سئو<input value={form.seo_title??''} onChange={e=>field('seo_title',e.target.value)}/>{errors('seo_title')}</label><label>توضیح سئو<textarea value={form.seo_description??''} onChange={e=>field('seo_description',e.target.value)}/>{errors('seo_description')}</label><label className="checkbox"><input type="checkbox" checked={form.noindex} onChange={e=>field('noindex',e.target.checked)}/>عدم ایندکس این صفحه</label></details>
 <label>وضعیت<select value={form.status} onChange={e=>field('status',e.target.value)}>{Object.entries(statuses).map(([key,label])=><option value={key} key={key}>{label}</option>)}</select></label>
 {form.published_at&&<p className="muted">زمان انتشار: {new Date(form.published_at).toLocaleString('fa-IR')}</p>}
 <div className="editor-actions"><button className="btn btn-primary" disabled={saving}>{saving?'در حال ذخیره…':'ذخیره محتوا'}</button><button type="button" className="btn btn-ghost" disabled={saving} onClick={()=>{if(window.confirm('تغییرات ذخیره‌نشده کنار گذاشته شوند؟'))setEditing(undefined);}}>بازگشت به فهرست</button></div></form></section>:<>
 <div className="admin-toolbar"><label className="search-label">جست‌وجو در عنوان<input type="search" value={query} onChange={e=>{setQuery(e.target.value);setNumber(1);}} placeholder="عنوان محتوا…"/></label><button className="btn btn-primary" onClick={()=>edit(null)}>+ محتوای جدید</button></div>
 <section className="card table-card" aria-busy={loading}>{loading?<p className="empty" role="status">در حال بارگذاری…</p>:page?.data.length?<div className="table-scroll"><table><thead><tr><th>عنوان</th><th>نوع</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody>{page.data.map(item=><tr key={item.id}><td><strong>{item.title}</strong><small dir="ltr">{item.path}</small>{item.migration_source?.includes('preview')&&<small>پیش‌نمایش قالب · نیازمند تطبیق با دیتابیس</small>}</td><td>{types[item.type]}</td><td><span className={`status status-${item.status}`}>{statuses[item.status]}</span></td><td><button onClick={()=>edit(item)}>ویرایش</button>{item.status==='published'&&<a href={`${baseUrl}${item.path}`} target="_blank" rel="noreferrer">مشاهده ↗</a>}</td></tr>)}</tbody></table></div>:<div className="empty"><h2>محتوایی در این فهرست نیست</h2><p className="muted">محتوای جدید بسازید یا فیلتر جست‌وجو را تغییر دهید.</p></div>}</section>
 <nav className="pagination" aria-label="صفحه‌بندی"><button disabled={number<=1||loading} onClick={()=>setNumber(x=>x-1)}>قبلی</button><span>{page?.total??0} محتوا · صفحه {number} از {page?.last_page??1}</span><button disabled={!page||number>=page.last_page||loading} onClick={()=>setNumber(x=>x+1)}>بعدی</button></nav></>}
 </>}
 </main></div>;
}
const root=document.getElementById('admin-root');if(root)createRoot(root).render(<App/>);
