'use client'
import { useState } from 'react'

const ADMIN_PASSWORD = 'lrack2025'

type PostMeta = { slug: string; title: string; date: string; excerpt: string }

function PostEditor({ post, onSave, onCancel }: { post?: PostMeta & { content?: string }; onSave: (d: any) => void; onCancel: () => void }) {
  const [title, setTitle] = useState(post?.title ?? '')
  const [date, setDate] = useState(post?.date ?? new Date().toISOString().slice(0, 10))
  const [excerpt, setExcerpt] = useState(post?.excerpt ?? '')
  const [content, setContent] = useState(post?.content ?? '')
  const ipt: React.CSSProperties = { width: '100%', padding: '8px 10px', border: '1px solid var(--border)', borderRadius: 7, fontSize: 13, background: 'var(--card-bg)', color: 'var(--heading)', boxSizing: 'border-box' }
  const lbl: React.CSSProperties = { fontSize: 11.5, fontWeight: 500, color: 'var(--body)', display: 'block', marginBottom: 4 }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10 }}>
        <div><label style={lbl}>Title</label><input value={title} onChange={e=>setTitle(e.target.value)} style={ipt} /></div>
        <div><label style={lbl}>Date</label><input type="date" value={date} onChange={e=>setDate(e.target.value)} style={{...ipt,width:145}} /></div>
      </div>
      <div><label style={lbl}>Excerpt (shown on blog listing)</label><input value={excerpt} onChange={e=>setExcerpt(e.target.value)} style={ipt} /></div>
      <div><label style={lbl}>Content (Markdown)</label><textarea value={content} onChange={e=>setContent(e.target.value)} rows={16} style={{...ipt,resize:'vertical',fontFamily:'monospace',fontSize:12.5}} /></div>
      <div style={{ display: 'flex', gap: 10 }}>
        <button className="btn-gold" style={{ border: 'none', cursor: 'pointer', padding: '8px 20px' }} onClick={() => onSave({ title, date, excerpt, content })}>Save Post</button>
        <button className="btn-ghost" style={{ border: '1px solid var(--border)', cursor: 'pointer', padding: '8px 20px' }} onClick={onCancel}>Cancel</button>
      </div>
    </div>
  )
}

export default function AdminPanel() {
  const [authed, setAuthed] = useState(false)
  const [pw, setPw] = useState('')
  const [err, setErr] = useState(false)
  const [view, setView] = useState<'list'|'new'|'edit'>('list')
  const [notice, setNotice] = useState('')

  if (!authed) return (
    <div style={{ maxWidth: 380, margin: '8rem auto', textAlign: 'center' }}>
      <div style={{ fontSize: 28, marginBottom: 12 }}>🔐</div>
      <h1 style={{ fontSize: 20, marginBottom: 20 }}>Admin Login</h1>
      <input type="password" value={pw} onChange={e=>setPw(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter'){if(pw===ADMIN_PASSWORD){setAuthed(true);setErr(false)}else setErr(true)} }}
        placeholder="Password" style={{ width:'100%', padding:'9px 12px', border:`1px solid ${err?'#e05252':'var(--border)'}`, borderRadius:8, fontSize:14, background:'var(--card-bg)', color:'var(--heading)', boxSizing:'border-box', marginBottom:8 }} />
      {err && <div style={{ fontSize:12, color:'#e05252', marginBottom:8 }}>Incorrect password</div>}
      <button className="btn-gold" style={{ width:'100%', border:'none', cursor:'pointer', padding:'9px' }} onClick={() => { if(pw===ADMIN_PASSWORD){setAuthed(true);setErr(false)}else setErr(true) }}>Login</button>
    </div>
  )

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:24 }}>
        <h1 style={{ fontSize:20 }}>Blog CMS</h1>
        <div style={{ display:'flex', gap:10 }}>
          {view==='list' && <button className="btn-gold" style={{ border:'none', cursor:'pointer', padding:'7px 16px', fontSize:13 }} onClick={()=>setView('new')}>+ New Post</button>}
          <button className="btn-ghost" style={{ border:'1px solid var(--border)', cursor:'pointer', padding:'7px 14px', fontSize:12 }} onClick={()=>setAuthed(false)}>Log out</button>
        </div>
      </div>
      {notice && <div style={{ padding:'10px 14px', background:'rgba(52,168,83,0.08)', border:'0.5px solid rgba(52,168,83,0.3)', borderRadius:8, fontSize:13, color:'#2d7a3a', marginBottom:18 }}>{notice}</div>}
      {view === 'list' && (
        <div>
          <p style={{ fontSize:13, color:'var(--body)', marginBottom:18 }}>Blog posts are stored as Markdown files in <code style={{fontSize:12, background:'var(--section-alt)', padding:'2px 5px', borderRadius:4}}>content/posts/</code>. Create or edit files there directly, or use this panel to preview and manage them.</p>
          <div style={{ padding:'14px', border:'0.5px solid var(--border)', borderRadius:10, background:'var(--card-bg)', fontSize:13, color:'var(--body)', lineHeight:1.7 }}>
            <strong style={{ color:'var(--heading)' }}>To create a new post:</strong> click "+ New Post" above, fill in the form, then copy the generated Markdown into a new <code style={{fontSize:12, background:'var(--section-alt)', padding:'2px 5px', borderRadius:4}}>.md</code> file in <code style={{fontSize:12, background:'var(--section-alt)', padding:'2px 5px', borderRadius:4}}>content/posts/</code>.
            <br/><br/>
            <strong style={{ color:'var(--heading)' }}>File naming:</strong> The filename (without <code style={{fontSize:12}}>.md</code>) becomes the URL slug. Example: <code style={{fontSize:12}}>how-to-measure.md</code> → <code style={{fontSize:12}}>/blog/how-to-measure</code>.
            <br/><br/>
            <strong style={{ color:'var(--heading)' }}>Current posts:</strong> 3 sample posts included. Add more by creating <code style={{fontSize:12}}>.md</code> files with the frontmatter format shown below.
          </div>
          <div style={{ marginTop:18, padding:'14px', border:'0.5px solid var(--border)', borderRadius:10, background:'var(--section-alt)', fontFamily:'monospace', fontSize:12, lineHeight:1.8, color:'var(--body)' }}>
            {`---\ntitle: "Your Post Title"\ndate: "2025-12-01"\nexcerpt: "One-line summary shown on blog listing."\n---\n\nYour Markdown content here...`}
          </div>
        </div>
      )}
      {view === 'new' && (
        <PostEditor onCancel={()=>setView('list')} onSave={(d) => {
          const slug = d.title.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')
          const md = `---\ntitle: "${d.title}"\ndate: "${d.date}"\nexcerpt: "${d.excerpt}"\n---\n\n${d.content}`
          navigator.clipboard?.writeText(md).catch(()=>{})
          setNotice(`Post content copied to clipboard! Save it as: content/posts/${slug}.md`)
          setView('list')
        }} />
      )}
    </div>
  )
}
