// ============================================================
// Admin panel — hidden #/admin route. Edits persist via ContentStore.
// Front-end only: the login is cosmetic, not real security.
// Exports window.AdminPanel. Load after content-store.js + React.
// ============================================================

(function () {
  const { useState, useEffect, useRef } = React;
  const CS = window.ContentStore;
  const SUB = window.Submissions;
  const LANGS = ['en', 'ge'];
  const ADMIN_EMAIL = 'giorgi@powerbi.ge';
  const ADMIN_PASS  = 'DA@admin2026';
  const AUTH_KEY    = '__da_adm';

  // =========================================================
  // Login gate
  // =========================================================
  function LoginGate({ children }) {
    const [authed, setAuthed] = useState(() => sessionStorage.getItem(AUTH_KEY) === '1');
    const [email, setEmail]   = useState('');
    const [pass, setPass]     = useState('');
    const [err, setErr]       = useState('');
    const [shake, setShake]   = useState(false);
    const passRef = useRef(null);

    if (authed) return children;

    const submit = (e) => {
      e.preventDefault();
      if (email.trim().toLowerCase() === ADMIN_EMAIL && pass === ADMIN_PASS) {
        sessionStorage.setItem(AUTH_KEY, '1');
        setAuthed(true);
      } else {
        setErr('Wrong email or password.');
        setShake(true);
        setTimeout(() => setShake(false), 600);
        setPass('');
        passRef.current && passRef.current.focus();
      }
    };

    return (
      <div className="adm-login-wrap">
        <form className={`adm-login-box ${shake ? 'adm-shake' : ''}`} onSubmit={submit} noValidate>
          <div className="adm-login-logo"><span className="logo-mark">DA</span></div>
          <h1 className="adm-login-title">Admin login</h1>
          <p className="adm-login-sub">This area is restricted.</p>
          <label className="adm-field">
            <span className="adm-label">Email</span>
            <input className="adm-input" type="email" autoComplete="username" value={email}
              onChange={(e) => { setEmail(e.target.value); setErr(''); }}
              placeholder="yourname@example.com" required />
          </label>
          <label className="adm-field">
            <span className="adm-label">Password</span>
            <input className="adm-input" type="password" ref={passRef} autoComplete="current-password"
              value={pass} onChange={(e) => { setPass(e.target.value); setErr(''); }} required />
          </label>
          {err && <p className="adm-login-err">{err}</p>}
          <button className="adm-btn adm-btn-primary adm-login-btn" type="submit">Sign in</button>
        </form>
      </div>
    );
  }

  // ---- icons ----
  const AI = ({ d, size = 18, fill }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill || 'none'} stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{d}</svg>
  );
  const ICONS = {
    dash: <><rect x="3" y="3" width="7" height="9" rx="1.5" /><rect x="14" y="3" width="7" height="5" rx="1.5" /><rect x="14" y="12" width="7" height="9" rx="1.5" /><rect x="3" y="16" width="7" height="5" rx="1.5" /></>,
    video: <><rect x="3" y="5" width="18" height="14" rx="2.5" /><path d="M10 9l5 3-5 3z" /></>,
    doc: <><path d="M6 2h8l4 4v16H6z" /><path d="M14 2v4h4" /><path d="M9 13h6M9 17h6" /></>,
    image: <><rect x="3" y="4" width="18" height="16" rx="2" /><circle cx="9" cy="10" r="2" /><path d="M21 16l-5-5L5 20" /></>,
    inbox: <><path d="M3 13h5l1.5 3h5L16 13h5" /><path d="M5 5h14l2 8v6H3v-6z" /></>,
    type: <><path d="M4 7V5h16v2M9 19h6M12 5v14" /></>,
    plus: <><path d="M12 5v14M5 12h14" /></>,
    trash: <><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13" /></>,
    up: <path d="M6 14l6-6 6 6" />,
    down: <path d="M6 10l6 6 6-6" />,
    x: <><path d="M6 6l12 12M18 6L6 18" /></>,
    eye: <><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z" /><circle cx="12" cy="12" r="3" /></>,
    reset: <><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 4v4h4" /></>,
  };
  const Icn = ({ name, size }) => <AI d={ICONS[name]} size={size} />;

  // ---- field atoms ----
  function Field({ label, value, onChange, textarea, mono, placeholder, type }) {
    return (
      <label className="adm-field">
        {label && <span className="adm-label">{label}</span>}
        {textarea ?
          <textarea className={`adm-input ${mono ? 'mono' : ''}`} value={value || ''} placeholder={placeholder} rows={3} onChange={(e) => onChange(e.target.value)} /> :
          <input className={`adm-input ${mono ? 'mono' : ''}`} type={type || 'text'} value={value == null ? '' : value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />}
      </label>
    );
  }
  function Toggle({ label, on, onChange }) {
    return (
      <button type="button" className={`adm-toggle ${on ? 'on' : ''}`} onClick={() => onChange(!on)}>
        <span className="adm-toggle-dot" />{label}
      </button>
    );
  }
  function IconBtn({ name, onClick, title, danger }) {
    return <button type="button" className={`adm-iconbtn ${danger ? 'danger' : ''}`} title={title} onClick={onClick}><Icn name={name} size={15} /></button>;
  }

  // ---- collection helpers (mirror structural edits across both langs) ----
  const items = (lang, path) => CS.value(lang, path) || [];
  const setItems = (lang, path, arr) => CS.set(lang, path, arr);
  const editLoc = (lang, path, i, patch) => setItems(lang, path, items(lang, path).map((it, idx) => idx === i ? { ...it, ...patch } : it));
  const editGlobal = (path, i, patch) => LANGS.forEach((L) => editLoc(L, path, i, patch));
  const addItem = (path, blank) => LANGS.forEach((L) => setItems(L, path, [...items(L, path), { ...blank }]));
  const delItem = (path, i) => LANGS.forEach((L) => setItems(L, path, items(L, path).filter((_, idx) => idx !== i)));
  const moveItem = (path, i, dir) => LANGS.forEach((L) => {
    const a = [...items(L, path)]; const j = i + dir; if (j < 0 || j >= a.length) return;
    [a[i], a[j]] = [a[j], a[i]]; setItems(L, path, a);
  });

  // =========================================================
  // Dashboard
  // =========================================================
  function Dashboard({ lang, go }) {
    const c = CS.get(lang);
    const courses = c.videoCourses.items;
    const lessons = courses.reduce((a, x) => a + x.lessons.length, 0);
    const subs = SUB.all();
    const stats = [
      { k: 'Video courses', v: courses.length, tab: 'video' },
      { k: 'Total lessons', v: lessons, tab: 'video' },
      { k: 'Blog posts', v: c.blog.items.length, tab: 'blog' },
      { k: 'Gallery projects', v: c.gallery.items.length, tab: 'gallery' },
      { k: 'Inbox messages', v: subs.length, tab: 'inbox' },
    ];
    return (
      <div className="adm-page">
        <h2 className="adm-h2">Overview</h2>
        <p className="adm-muted">Manage everything on the site. Changes save instantly to this browser and update the live site.</p>
        <div className="adm-stats">
          {stats.map((s) =>
            <button key={s.k} className="adm-stat" onClick={() => go(s.tab)}>
              <div className="adm-stat-v">{s.v}</div>
              <div className="adm-stat-k">{s.k}</div>
            </button>)}
        </div>
        <div className="adm-quick">
          <button className="adm-btn" onClick={() => go('video')}><Icn name="plus" size={15} /> Add a video course</button>
          <button className="adm-btn" onClick={() => go('blog')}><Icn name="plus" size={15} /> Write a blog post</button>
          <button className="adm-btn" onClick={() => go('inbox')}><Icn name="inbox" size={15} /> View messages</button>
        </div>
      </div>
    );
  }

  // =========================================================
  // Video courses
  // =========================================================
  function VideoAdmin({ lang }) {
    const P = 'videoCourses.items';
    const list = items(lang, P);
    const [open, setOpen] = useState(0);
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Video courses</h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { id: 'course-' + Date.now(), title: 'New course', level: 'Beginner', price: '0', currency: 'GEL', hue: 210, accessCode: '', lessons: [] })}><Icn name="plus" size={15} /> New course</button>
        </div>
        {list.map((c, ci) =>
          <div key={c.id || ci} className="adm-card">
            <div className="adm-card-head" onClick={() => setOpen(open === ci ? -1 : ci)}>
              <span className="adm-swatch" style={{ background: `hsl(${c.hue || 210} 68% 46%)` }} />
              <span className="adm-card-title">{c.title}</span>
              <span className="adm-card-sub mono">{c.lessons.length} lessons · {c.price} {c.currency}</span>
              <span className="adm-card-tools">
                <IconBtn name="up" title="Move up" onClick={(e) => { moveItem(P, ci, -1); }} />
                <IconBtn name="down" title="Move down" onClick={() => moveItem(P, ci, 1)} />
                <IconBtn name="trash" danger title="Delete course" onClick={() => { if (confirm('Delete this course?')) delItem(P, ci); }} />
                <Icn name={open === ci ? 'up' : 'down'} size={16} />
              </span>
            </div>
            {open === ci &&
              <div className="adm-card-body">
                <div className="adm-row">
                  <Field label={`Title (${lang.toUpperCase()})`} value={c.title} onChange={(v) => editLoc(lang, P, ci, { title: v })} />
                  <Field label={`Level (${lang.toUpperCase()})`} value={c.level} onChange={(v) => editLoc(lang, P, ci, { level: v })} />
                </div>
                <div className="adm-row">
                  <Field label="Price" value={c.price} onChange={(v) => editGlobal(P, ci, { price: v })} mono />
                  <Field label="Currency" value={c.currency} onChange={(v) => editGlobal(P, ci, { currency: v })} mono />
                  <Field label="Color hue (0–360)" value={c.hue} type="number" onChange={(v) => editGlobal(P, ci, { hue: Number(v) })} mono />
                  <Field label="Access code" value={c.accessCode} placeholder="PBI2026" onChange={(v) => editGlobal(P, ci, { accessCode: v })} mono />
                </div>
                <div className="adm-sub-head">
                  <span>Lessons</span>
                  <button className="adm-btn adm-btn-sm" onClick={() => LANGS.forEach((L) => editLoc(L, P, ci, { lessons: [...(items(L, P)[ci].lessons), { title: 'New lesson', duration: '00:00', vimeo: '', free: false }] }))}><Icn name="plus" size={13} /> Add lesson</button>
                </div>
                {c.lessons.map((l, li) =>
                  <div key={li} className="adm-lesson">
                    <span className="adm-lesson-n mono">{String(li + 1).padStart(2, '0')}</span>
                    <Field placeholder="Lesson title" value={l.title} onChange={(v) => editLoc(lang, P, ci, { lessons: c.lessons.map((x, k) => k === li ? { ...x, title: v } : x) })} />
                    <Field placeholder="mm:ss" value={l.duration} mono onChange={(v) => editGlobal(P, ci, { lessons: items('en', P)[ci].lessons.map((x, k) => k === li ? { ...x, duration: v } : x) })} />
                    <Field placeholder="Vimeo ID" value={l.vimeo} mono onChange={(v) => editGlobal(P, ci, { lessons: items('en', P)[ci].lessons.map((x, k) => k === li ? { ...x, vimeo: v } : x) })} />
                    <Toggle label="Free" on={l.free} onChange={(on) => editGlobal(P, ci, { lessons: items('en', P)[ci].lessons.map((x, k) => k === li ? { ...x, free: on } : x) })} />
                    <IconBtn name="trash" danger title="Delete lesson" onClick={() => LANGS.forEach((L) => editLoc(L, P, ci, { lessons: items(L, P)[ci].lessons.filter((_, k) => k !== li) }))} />
                  </div>)}
                {!c.lessons.length && <p className="adm-muted adm-empty">No lessons yet — add your first.</p>}
              </div>}
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Blog
  // =========================================================
  function CoverUpload({ cover, onChange }) {
    const ref = useRef(null);
    const pick = () => ref.current && ref.current.click();
    const onFile = (e) => {
      const file = e.target.files && e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = (ev) => onChange(ev.target.result);
      reader.readAsDataURL(file);
      e.target.value = '';
    };
    return (
      <div className="adm-cover-wrap">
        <span className="adm-label">Cover image</span>
        {cover
          ? <div className="adm-cover-preview">
              <img src={cover} alt="cover" className="adm-cover-img" />
              <button type="button" className="adm-cover-remove" onClick={() => onChange('')} title="Remove cover">
                <Icn name="x" size={13} />
              </button>
            </div>
          : <button type="button" className="adm-cover-pick" onClick={pick}>
              <Icn name="image" size={18} />
              <span>Upload cover image</span>
            </button>
        }
        <input ref={ref} type="file" accept="image/*" style={{ display: 'none' }} onChange={onFile} />
      </div>
    );
  }

  function BlogAdmin({ lang }) {
    const P = 'blog.items';
    const list = items(lang, P);
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Blog posts</h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { tag: 'Tag', date: '', readTime: '5 min', title: 'New post', excerpt: '', content: '', cover: '' })}><Icn name="plus" size={15} /> New post</button>
        </div>
        {list.map((b, i) =>
          <div key={i} className="adm-card">
            <div className="adm-card-body">
              <CoverUpload cover={b.cover || ''} onChange={(v) => editLoc(lang, P, i, { cover: v })} />
              <div className="adm-row">
                <Field label="Title" value={b.title} onChange={(v) => editLoc(lang, P, i, { title: v })} />
                <Field label="Tag" value={b.tag} onChange={(v) => editLoc(lang, P, i, { tag: v })} />
              </div>
              <div className="adm-row">
                <Field label="Date" value={b.date} onChange={(v) => editLoc(lang, P, i, { date: v })} mono />
                <Field label="Read time" value={b.readTime} onChange={(v) => editLoc(lang, P, i, { readTime: v })} mono />
              </div>
              <Field label="Excerpt" textarea value={b.excerpt} onChange={(v) => editLoc(lang, P, i, { excerpt: v })} />
              <Field label="Full article content (paragraphs — blank line = new paragraph)" textarea value={b.content || ''} onChange={(v) => editLoc(lang, P, i, { content: v })} />
              <div className="adm-card-foot">
                <IconBtn name="up" onClick={() => moveItem(P, i, -1)} title="Move up" />
                <IconBtn name="down" onClick={() => moveItem(P, i, 1)} title="Move down" />
                <IconBtn name="trash" danger onClick={() => { if (confirm('Delete this post?')) delItem(P, i); }} title="Delete" />
              </div>
            </div>
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Gallery
  // =========================================================
  const KINDS = ['restaurant', 'automotive', 'realestate', 'retail', 'restaurant2', 'construction', 'cosmetics', 'automotive2', 'retail2'];
  function GalleryAdmin({ lang }) {
    const P = 'gallery.items';
    const list = items(lang, P);
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Gallery projects</h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { title: 'New project', tag: 'Tag', desc: '', kind: 'retail' })}><Icn name="plus" size={15} /> New project</button>
        </div>
        <div className="adm-grid2">
          {list.map((g, i) =>
            <div key={i} className="adm-card">
              <div className="adm-card-body">
                <Field label="Title" value={g.title} onChange={(v) => editLoc(lang, P, i, { title: v })} />
                <div className="adm-row">
                  <Field label="Tag" value={g.tag} onChange={(v) => editLoc(lang, P, i, { tag: v })} />
                  <label className="adm-field">
                    <span className="adm-label">Thumbnail style</span>
                    <select className="adm-input mono" value={g.kind} onChange={(e) => editGlobal(P, i, { kind: e.target.value })}>
                      {KINDS.map((k) => <option key={k} value={k}>{k}</option>)}
                    </select>
                  </label>
                </div>
                <Field label="Description" textarea value={g.desc} onChange={(v) => editLoc(lang, P, i, { desc: v })} />
                <Field label="Report link (opens on click)" value={g.url} placeholder="https://app.powerbi.com/view?r=..." onChange={(v) => editGlobal(P, i, { url: v })} />
                <Field label="Preview embed URL (optional small window)" value={g.embed} placeholder="https://app.powerbi.com/view?r=..." onChange={(v) => editGlobal(P, i, { embed: v })} />
                {g.embed && <div style={{ margin: '8px 0', borderRadius: '6px', overflow: 'hidden', border: '1px solid var(--adm-border, #ddd)' }}><iframe src={g.embed} title={g.title} style={{ width: '100%', height: '160px', border: 0 }} /></div>}
                <div className="adm-card-foot">
                  <IconBtn name="up" onClick={() => moveItem(P, i, -1)} title="Move up" />
                  <IconBtn name="down" onClick={() => moveItem(P, i, 1)} title="Move down" />
                  <IconBtn name="trash" danger onClick={() => { if (confirm('Delete this project?')) delItem(P, i); }} title="Delete" />
                </div>
              </div>
            </div>)}
        </div>
      </div>
    );
  }

  // =========================================================
  // Submissions inbox
  // =========================================================
  function InboxAdmin() {
    const [, force] = useState(0);
    useEffect(() => SUB.subscribe(() => force((v) => v + 1)), []);
    const all = SUB.all();
    const fmt = (ts) => new Date(ts).toLocaleString();
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Messages <span className="adm-count">{all.length}</span></h2>
          {all.length > 0 && <button className="adm-btn" onClick={() => { if (confirm('Clear all messages?')) SUB.clear(); }}><Icn name="trash" size={14} /> Clear all</button>}
        </div>
        {!all.length && <div className="adm-blank"><Icn name="inbox" size={34} /><p>No messages yet. Submissions from the contact form land here.</p></div>}
        {all.map((m) =>
          <div key={m.ts} className="adm-msg">
            <div className="adm-msg-top">
              <div>
                <strong>{m.name || '—'}</strong>
                <span className="adm-msg-email mono">{m.email}</span>
              </div>
              <div className="adm-msg-meta">
                <span className="mono">{fmt(m.ts)}</span>
                <IconBtn name="trash" danger onClick={() => SUB.remove(m.ts)} title="Delete" />
              </div>
            </div>
            <div className="adm-msg-tags mono">
              {m.phone && <span>{m.phone}</span>}
              {m.service && <span className="adm-msg-svc">{m.service}</span>}
            </div>
            <p className="adm-msg-body">{m.message}</p>
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Hero Carousel
  // =========================================================
  function HeroCarouselAdmin() {
    const P = 'hero.carousel.items';
    const [lang] = useState('en');
    const list = items(lang, P);
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Hero Carousel</h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { image: '' })}><Icn name="plus" size={15} /> Add image</button>
        </div>
        <p className="adm-muted">Paste image URLs that will auto-rotate every 4 seconds with smooth fade transitions.</p>
        {list.map((c, i) =>
          <div key={i} className="adm-card">
            <div className="adm-card-body">
              {c.image && <div style={{ marginBottom: '12px' }}><img src={c.image} alt="" style={{ maxWidth: '300px', maxHeight: '160px', borderRadius: '6px' }} /></div>}
              <Field label="Image URL" value={c.image} placeholder="https://example.com/image.png" onChange={(v) => editGlobal(P, i, { image: v })} />
              <div className="adm-card-foot">
                <IconBtn name="up" onClick={() => moveItem(P, i, -1)} title="Move up" />
                <IconBtn name="down" onClick={() => moveItem(P, i, 1)} title="Move down" />
                <IconBtn name="trash" danger onClick={() => { if (confirm('Delete this image?')) delItem(P, i); }} title="Delete" />
              </div>
            </div>
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Clients
  // =========================================================
  function ClientsAdmin() {
    const P = 'testimonials.clients.items';
    const [lang] = useState('en');
    const list = items(lang, P);

    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Clients</h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { name: 'New client', logo: '' })}><Icn name="plus" size={15} /> Add client</button>
        </div>
        {list.map((c, i) =>
          <div key={i} className="adm-card">
            <div className="adm-card-body">
              {c.logo && <div style={{ marginBottom: '12px' }}><img src={c.logo} alt={c.name} style={{ maxWidth: '200px', maxHeight: '100px', borderRadius: '6px' }} /></div>}
              <Field label="Logo URL" value={c.logo} placeholder="https://example.com/logo.png" onChange={(v) => editGlobal(P, i, { logo: v })} />
              <Field label="Client name" value={c.name} onChange={(v) => editGlobal(P, i, { name: v })} />
              <div className="adm-card-foot">
                <IconBtn name="up" onClick={() => moveItem(P, i, -1)} title="Move up" />
                <IconBtn name="down" onClick={() => moveItem(P, i, 1)} title="Move down" />
                <IconBtn name="trash" danger onClick={() => { if (confirm('Delete this client?')) delItem(P, i); }} title="Delete" />
              </div>
            </div>
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Reports
  // =========================================================
  function ReportsAdmin() {
    const P = 'reports.items';
    const [lang] = useState('en');
    const list = items(lang, P);
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Reports</h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { title: 'New report', desc: '', embed: '', url: '' })}><Icn name="plus" size={15} /> Add report</button>
        </div>
        <p className="adm-muted">Embed a published Power BI report by pasting its <strong>publish-to-web embed URL</strong>. Optionally add a link to open the full report in a new tab.</p>
        {list.map((c, i) =>
          <div key={i} className="adm-card">
            <div className="adm-card-body">
              {c.embed && <div style={{ marginBottom: '12px', borderRadius: '6px', overflow: 'hidden', border: '1px solid var(--adm-border, #ddd)' }}><iframe src={c.embed} title={c.title} style={{ width: '100%', height: '220px', border: 0 }} /></div>}
              <Field label="Report title" value={c.title} onChange={(v) => editGlobal(P, i, { title: v })} />
              <Field label="Description" textarea value={c.desc} onChange={(v) => editGlobal(P, i, { desc: v })} />
              <Field label="Embed URL (Power BI publish-to-web)" value={c.embed} placeholder="https://app.powerbi.com/view?r=..." onChange={(v) => editGlobal(P, i, { embed: v })} />
              <Field label="Open-full-report link (optional)" value={c.url} placeholder="https://app.powerbi.com/..." onChange={(v) => editGlobal(P, i, { url: v })} />
              <div className="adm-card-foot">
                <IconBtn name="up" onClick={() => moveItem(P, i, -1)} title="Move up" />
                <IconBtn name="down" onClick={() => moveItem(P, i, 1)} title="Move down" />
                <IconBtn name="trash" danger onClick={() => { if (confirm('Delete this report?')) delItem(P, i); }} title="Delete" />
              </div>
            </div>
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Testimonials
  // =========================================================
  function TestimonialsAdmin({ lang }) {
    const P = 'testimonials.items';
    const list = items(lang, P);
    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Testimonials <span className="adm-langtag mono">editing {lang.toUpperCase()}</span></h2>
          <button className="adm-btn adm-btn-primary" onClick={() => addItem(P, { quote: '', name: '', role: '', initials: '' })}><Icn name="plus" size={15} /> Add testimonial</button>
        </div>
        <p className="adm-muted">Use the language switch in the top bar to edit the other language. Avatar initials are auto-generated from the name unless you set them.</p>
        {list.map((c, i) =>
          <div key={i} className="adm-card">
            <div className="adm-card-body">
              <Field label="Quote" textarea value={c.quote} onChange={(v) => editLoc(lang, P, i, { quote: v })} />
              <div className="adm-row">
                <Field label="Name" value={c.name} onChange={(v) => editLoc(lang, P, i, { name: v })} />
                <Field label="Role / company" value={c.role} onChange={(v) => editLoc(lang, P, i, { role: v })} />
              </div>
              <Field label="Avatar initials (optional)" value={c.initials} placeholder="auto from name" onChange={(v) => editLoc(lang, P, i, { initials: v })} />
              <div className="adm-card-foot">
                <IconBtn name="up" onClick={() => moveItem(P, i, -1)} title="Move up" />
                <IconBtn name="down" onClick={() => moveItem(P, i, 1)} title="Move down" />
                <IconBtn name="trash" danger onClick={() => { if (confirm('Delete this testimonial?')) delItem(P, i); }} title="Delete" />
              </div>
            </div>
          </div>)}
      </div>
    );
  }

  // =========================================================
  // Courses (training pricing cards)
  // =========================================================
  function StringListEditor({ label, lang, path }) {
    const list = CS.value(lang, path) || [];
    const save = (arr) => CS.set(lang, path, arr);
    return (
      <div style={{ marginTop: '10px' }}>
        <span className="adm-label">{label}</span>
        {list.map((s, i) =>
          <div key={i} className="adm-row" style={{ alignItems: 'center', marginBottom: '6px' }}>
            <Field value={s} onChange={(v) => save(list.map((x, idx) => idx === i ? v : x))} />
            <IconBtn name="up" onClick={() => { if (i > 0) { const a = [...list];[a[i - 1], a[i]] = [a[i], a[i - 1]]; save(a); } }} title="Move up" />
            <IconBtn name="trash" danger onClick={() => save(list.filter((_, idx) => idx !== i))} title="Remove" />
          </div>)}
        <button type="button" className="adm-btn" onClick={() => save([...list, ''])}><Icn name="plus" size={14} /> Add</button>
      </div>
    );
  }

  function CoursesAdmin({ lang }) {
    const txt = (p) => CS.value(lang, p);
    const setTxt = (p, v) => CS.set(lang, p, v);
    const plans = [['solo', 'Solo / Individual plan'], ['group', 'Group plan']];
    return (
      <div className="adm-page">
        <h2 className="adm-h2">Courses <span className="adm-langtag mono">editing {lang.toUpperCase()}</span></h2>
        <p className="adm-muted">Edit the training pricing cards. Use the language switch in the top bar for the other language.</p>
        <div className="adm-card"><div className="adm-card-body">
          <h3 className="adm-h3">Section headings</h3>
          <Field label="Eyebrow" value={txt('courses.eyebrow')} onChange={(v) => setTxt('courses.eyebrow', v)} />
          <Field label="Title" textarea value={txt('courses.title')} onChange={(v) => setTxt('courses.title', v)} />
          <Field label="Subtitle" value={txt('courses.subtitle')} onChange={(v) => setTxt('courses.subtitle', v)} />
          <Field label="Note" value={txt('courses.note')} onChange={(v) => setTxt('courses.note', v)} />
          <Field label="Syllabus link label" value={txt('courses.syllabusCta')} onChange={(v) => setTxt('courses.syllabusCta', v)} />
        </div></div>
        {plans.map(([key, label]) => {
          const b = `courses.${key}`;
          return (
            <div key={key} className="adm-card"><div className="adm-card-body">
              <h3 className="adm-h3">{label}</h3>
              <div className="adm-row">
                <Field label="Badge" value={txt(`${b}.badge`)} onChange={(v) => setTxt(`${b}.badge`, v)} />
                <Field label="Name" value={txt(`${b}.name`)} onChange={(v) => setTxt(`${b}.name`, v)} />
              </div>
              <div className="adm-row">
                <Field label="Format" value={txt(`${b}.format`)} onChange={(v) => setTxt(`${b}.format`, v)} />
                <Field label="Price" value={txt(`${b}.price`)} onChange={(v) => setTxt(`${b}.price`, v)} />
                <Field label="Currency / unit" value={txt(`${b}.currency`)} onChange={(v) => setTxt(`${b}.currency`, v)} />
              </div>
              <Field label="Button text (CTA)" value={txt(`${b}.cta`)} onChange={(v) => setTxt(`${b}.cta`, v)} />
              <StringListEditor label="Features (checkmarks)" lang={lang} path={`${b}.features`} />
              <StringListEditor label="Curriculum topics (chips)" lang={lang} path={`${b}.topics`} />
            </div></div>
          );
        })}
      </div>
    );
  }

  // =========================================================
  // Statistics
  // =========================================================
  function StatBar({ rows, total }) {
    const max = rows.reduce((m, r) => Math.max(m, r[1]), 0) || 1;
    if (!rows.length) return <p className="adm-muted">No data yet.</p>;
    return (
      <div className="adm-statbars">
        {rows.map(([label, n]) =>
          <div key={label} className="adm-statbar">
            <div className="adm-statbar-label" title={label}>{label || 'Unknown'}</div>
            <div className="adm-statbar-track"><div className="adm-statbar-fill" style={{ width: `${(n / max) * 100}%` }} /></div>
            <div className="adm-statbar-val">{n}{total ? <span className="adm-statbar-pct"> · {Math.round((n / total) * 100)}%</span> : null}</div>
          </div>)}
      </div>
    );
  }

  function StatsAdmin() {
    const [visits, setVisits] = useState(null);
    const [reloadKey, setReloadKey] = useState(0);
    useEffect(() => {
      let alive = true;
      setVisits(null);
      (async () => {
        const v = (window.SupabaseClient && window.SupabaseClient.getVisits) ? await window.SupabaseClient.getVisits(5000) : [];
        if (alive) setVisits(v);
      })();
      return () => { alive = false; };
    }, [reloadKey]);

    if (visits === null) {
      return <div className="adm-page"><h2 className="adm-h2">Statistics</h2><p className="adm-muted">Loading…</p></div>;
    }

    const now = Date.now();
    const dayMs = 86400000;
    const todayStr = new Date().toDateString();
    const total = visits.length;
    const today = visits.filter((v) => new Date(v.created_at).toDateString() === todayStr).length;
    const last7 = visits.filter((v) => now - new Date(v.created_at).getTime() < 7 * dayMs).length;
    const last30 = visits.filter((v) => now - new Date(v.created_at).getTime() < 30 * dayMs).length;

    const countBy = (key, clean) => {
      const m = {};
      visits.forEach((v) => { let k = v[key] || 'Unknown'; if (clean) k = clean(k); m[k] = (m[k] || 0) + 1; });
      return Object.entries(m).sort((a, b) => b[1] - a[1]);
    };
    const refClean = (r) => {
      if (!r || r === 'Direct') return 'Direct';
      try { return new URL(r).hostname.replace(/^www\./, ''); } catch (e) { return r; }
    };

    const stats = [
      { k: 'Total visits', v: total },
      { k: 'Today', v: today },
      { k: 'Last 7 days', v: last7 },
      { k: 'Last 30 days', v: last30 },
    ];

    return (
      <div className="adm-page">
        <div className="adm-page-head">
          <h2 className="adm-h2">Statistics</h2>
          <button className="adm-btn" onClick={() => setReloadKey((k) => k + 1)}><Icn name="reset" size={14} /> Refresh</button>
        </div>
        <p className="adm-muted">Visitor analytics from the live site. Updates in real time as people browse.</p>
        <div className="adm-stats">
          {stats.map((s) => <div key={s.k} className="adm-stat"><div className="adm-stat-v">{s.v}</div><div className="adm-stat-k">{s.k}</div></div>)}
        </div>
        {total === 0 ?
          <div className="adm-card"><div className="adm-card-body"><p className="adm-muted">No visits recorded yet. Once people open the site, data will appear here. (Make sure the <code>visits</code> table exists in Supabase.)</p></div></div> :
          <div className="adm-grid2">
            <div className="adm-card"><div className="adm-card-body"><h3 className="adm-h3">Top pages</h3><StatBar rows={countBy('page')} total={total} /></div></div>
            <div className="adm-card"><div className="adm-card-body"><h3 className="adm-h3">Where they come from</h3><StatBar rows={countBy('referrer', refClean)} total={total} /></div></div>
            <div className="adm-card"><div className="adm-card-body"><h3 className="adm-h3">Device</h3><StatBar rows={countBy('device')} total={total} /></div></div>
            <div className="adm-card"><div className="adm-card-body"><h3 className="adm-h3">Browser</h3><StatBar rows={countBy('browser')} total={total} /></div></div>
            <div className="adm-card"><div className="adm-card-body"><h3 className="adm-h3">OS</h3><StatBar rows={countBy('os')} total={total} /></div></div>
            <div className="adm-card"><div className="adm-card-body"><h3 className="adm-h3">Language</h3><StatBar rows={countBy('lang')} total={total} /></div></div>
          </div>}
      </div>
    );
  }

  // =========================================================
  // Site text
  // =========================================================
  const TEXT_FIELDS = [
    ['hero.eyebrow', 'Hero — eyebrow', false],
    ['hero.sub', 'Hero — subtext', true],
    ['services.title', 'Services — title', true],
    ['services.subtitle', 'Services — subtitle', false],
    ['courses.title', 'Courses — title', true],
    ['courses.subtitle', 'Courses — subtitle', false],
    ['courses.note', 'Courses — note', false],
    ['videoCourses.title', 'Video courses — title', false],
    ['videoCourses.subtitle', 'Video courses — subtitle', true],
    ['gallery.title', 'Gallery — title', false],
    ['gallery.subtitle', 'Gallery — subtitle', false],
    ['blog.title', 'Blog — title', false],
    ['blog.subtitle', 'Blog — subtitle', true],
    ['contact.title', 'Contact — title', true],
    ['contact.subtitle', 'Contact — subtitle', false],
    ['footer.tagline', 'Footer — tagline', true],
  ];
  function TextAdmin({ lang }) {
    const head = CS.value(lang, 'hero.headline') || ['', '', ''];
    const setHead = (idx, v) => CS.set(lang, 'hero.headline', head.map((x, i) => i === idx ? v : x));
    return (
      <div className="adm-page">
        <h2 className="adm-h2">Site text <span className="adm-langtag mono">editing {lang.toUpperCase()}</span></h2>
        <p className="adm-muted">Use the language switch in the top bar to edit the other language.</p>
        <div className="adm-card">
          <div className="adm-card-body">
            <span className="adm-label">Hero headline (3 parts — middle is the highlighted word)</span>
            <div className="adm-row">
              <Field value={head[0]} onChange={(v) => setHead(0, v)} />
              <Field value={head[1]} onChange={(v) => setHead(1, v)} />
              <Field value={head[2]} onChange={(v) => setHead(2, v)} />
            </div>
          </div>
        </div>
        <div className="adm-card"><div className="adm-card-body">
          {TEXT_FIELDS.map(([p, label, ta]) =>
            <Field key={p} label={label} textarea={ta} value={CS.value(lang, p)} onChange={(v) => CS.set(lang, p, v)} />)}
        </div></div>
      </div>
    );
  }

  // =========================================================
  // Shell
  // =========================================================
  const TABS = [
    { id: 'dashboard', label: 'Dashboard', icon: 'dash' },
    { id: 'stats', label: 'Statistics', icon: 'dash' },
    { id: 'hero', label: 'Hero Carousel', icon: 'image' },
    { id: 'clients', label: 'Clients', icon: 'users' },
    { id: 'testimonials', label: 'Testimonials', icon: 'inbox' },
    { id: 'courses', label: 'Courses', icon: 'doc' },
    { id: 'reports', label: 'Reports', icon: 'dash' },
    { id: 'video', label: 'Video courses', icon: 'video' },
    { id: 'blog', label: 'Blog', icon: 'doc' },
    { id: 'gallery', label: 'Gallery', icon: 'image' },
    { id: 'inbox', label: 'Messages', icon: 'inbox' },
    { id: 'text', label: 'Site text', icon: 'type' },
  ];

  function AdminPanel({ lang, setLang, theme }) {
    const [tab, setTab] = useState('dashboard');
    const [editLang, setEditLang] = useState(lang || 'en');
    const [, force] = useState(0);
    useEffect(() => CS.subscribe(() => force((v) => v + 1)), []);

    const exit = () => { window.location.hash = ''; };

    return (
      <div className="adm" data-theme={theme}>
        <header className="adm-top">
          <div className="adm-top-l">
            <span className="adm-logo"><span className="logo-mark">DA</span> Admin</span>
            <span className="adm-who mono">{ADMIN_EMAIL}</span>
          </div>
          <div className="adm-top-r">
            <div className="adm-langsw">
              {LANGS.map((L) =>
                <button key={L} className={`adm-langbtn ${editLang === L ? 'on' : ''}`} onClick={() => setEditLang(L)}>{L === 'en' ? 'EN' : 'ქარ'}</button>)}
            </div>
            <button className="adm-btn" onClick={() => { if (confirm('Reset ALL content changes back to defaults? This cannot be undone.')) CS.reset(); }}><Icn name="reset" size={14} /> Reset</button>
            <button className="adm-btn adm-btn-primary" onClick={exit}><Icn name="eye" size={14} /> View site</button>
          </div>
        </header>
        <div className="adm-shell">
          <nav className="adm-side">
            {TABS.map((tb) =>
              <button key={tb.id} className={`adm-tab ${tab === tb.id ? 'on' : ''}`} onClick={() => setTab(tb.id)}>
                <Icn name={tb.icon} size={17} /> {tb.label}
              </button>)}
            <div className="adm-side-foot mono">{CS.hasOverrides() ? '● unsaved edits stored locally' : 'no custom edits yet'}</div>
          </nav>
          <main className="adm-main">
            {tab === 'dashboard' && <Dashboard lang={editLang} go={setTab} />}
            {tab === 'stats' && <StatsAdmin />}
            {tab === 'hero' && <HeroCarouselAdmin />}
            {tab === 'clients' && <ClientsAdmin />}
            {tab === 'testimonials' && <TestimonialsAdmin lang={editLang} />}
            {tab === 'courses' && <CoursesAdmin lang={editLang} />}
            {tab === 'reports' && <ReportsAdmin />}
            {tab === 'video' && <VideoAdmin lang={editLang} />}
            {tab === 'blog' && <BlogAdmin lang={editLang} />}
            {tab === 'gallery' && <GalleryAdmin lang={editLang} />}
            {tab === 'inbox' && <InboxAdmin />}
            {tab === 'text' && <TextAdmin lang={editLang} />}
          </main>
        </div>
      </div>
    );
  }

  function AdminGate(props) {
    return (
      <LoginGate>
        <AdminPanel {...props} />
      </LoginGate>
    );
  }

  window.AdminPanel = AdminGate;
})();
