/* admin-builder.jsx — 3-pane drag/click widget editor (Baukasten) */

let WID_SEQ = 100;
function makeWidget(type) {
  WID_SEQ += 1;
  return {
    id: 'w_' + WID_SEQ,
    type,
    props: defaultProps(type),
    meta: {
      widgetId: 'WG-' + String(WID_SEQ).padStart(4, '0'),
      pageId: 'PG-001',
      language: 'DE',
      version: 1,
      createdBy: 'M. Krause',
      updatedAt: 'gerade',
      trackingKey: 'trk_' + type + '_' + WID_SEQ,
    },
  };
}
function defaultProps(type) {
  switch (type) {
    case 'text': return { headline: 'Überschrift', body: 'Kurzer, sachlicher Textblock.' };
    case 'hero': return { headline: 'Bereit für deinen Dienststart.', cta: 'Vorbereitung starten' };
    case 'hinweis': return { tone: 'info', text: 'Kein offizielles Bundeswehr-Angebot.' };
    case 'faq': return { items: 3 };
    case 'buttons': return { count: 2, primary: 'Starten' };
    case 'checkliste': return { items: 4, title: 'Dienststart-Checkliste' };
    case 'download': return { file: 'packliste.pdf', label: 'Packliste (PDF)' };
    case 'social': return { network: 'Instagram', handle: '@rekruten.schmiede' };
    case 'kurskarte': return { title: 'Basisfitness', area: 'Fitness' };
    case 'kalender': return { weeks: 4 };
    case 'shopteaser': return { product: 'Alpha-Paket', price: '49,00 €' };
    case 'video': return { provider: 'YouTube', ratio: '16:9' };
    default: return {};
  }
}

const INITIAL_PAGE = () => ({
  title: 'Startseite',
  sections: [
    { id: 's1', name: 'Hero', widgets: [makeWidget('hero')] },
    { id: 's2', name: 'Schnellzugriff', widgets: [makeWidget('buttons'), makeWidget('checkliste')] },
    { id: 's3', name: 'Info', widgets: [makeWidget('text'), makeWidget('hinweis')] },
  ],
});

function WidgetPreview({ w }) {
  switch (w.type) {
    case 'hero':
      return (<div className="wp wp-hero"><div className="wp-hero__txt"><b>{w.props.headline}</b><span className="wp-btn">{w.props.cta}</span></div><div className="wp-hero__img">Bild</div></div>);
    case 'text':
      return (<div className="wp wp-text"><b>{w.props.headline}</b><span className="wp-lines"><i /><i /><i style={{ width: '70%' }} /></span></div>);
    case 'hinweis':
      return (<div className="wp wp-hinweis"><Icon name="info" size={16} /><span>{w.props.text}</span></div>);
    case 'faq':
      return (<div className="wp wp-faq">{Array.from({ length: w.props.items }).map((_, i) => <span key={i} className="wp-faq__q"><span>Frage {i + 1}</span><Icon name="chevronDown" size={13} /></span>)}</div>);
    case 'buttons':
      return (<div className="wp wp-buttons"><span className="wp-btn">{w.props.primary}</span>{Array.from({ length: w.props.count - 1 }).map((_, i) => <span key={i} className="wp-btn wp-btn--ghost">Aktion</span>)}</div>);
    case 'checkliste':
      return (<div className="wp wp-check"><b>{w.props.title}</b>{Array.from({ length: w.props.items }).map((_, i) => <span key={i} className="wp-check__row"><span className="wp-check__box" />Punkt {i + 1}</span>)}</div>);
    case 'download':
      return (<div className="wp wp-download"><Icon name="download" size={16} /><span>{w.props.label}</span><span className="mono wp-download__f">{w.props.file}</span></div>);
    case 'social':
      return (<div className="wp wp-social"><Icon name="instagram" size={16} /><span>{w.props.network}</span><span className="mono">{w.props.handle}</span></div>);
    case 'kurskarte':
      return (<div className="wp wp-kurs"><span className="wp-kurs__img">Bild</span><span className="wp-kurs__b"><b>{w.props.title}</b><span className="chip chip--neutral">{w.props.area}</span></span></div>);
    case 'kalender':
      return (<div className="wp wp-kal">{Array.from({ length: w.props.weeks }).map((_, i) => <span key={i} className="wp-kal__w"><span className="mono">KW {23 + i}</span></span>)}</div>);
    case 'shopteaser':
      return (<div className="wp wp-shop"><span className="wp-shop__img">Bild</span><span className="wp-shop__b"><b>{w.props.product}</b><span className="mono">{w.props.price}</span></span></div>);
    case 'video':
      return (<div className="wp wp-video"><Icon name="external" size={22} /><span className="mono">{w.props.provider} · {w.props.ratio}</span></div>);
    default: return <div className="wp">{w.type}</div>;
  }
}

function AdminBuilder() {
  const [page, setPage] = useState(INITIAL_PAGE);
  const [selSection, setSelSection] = useState('s2');
  const [selWidget, setSelWidget] = useState(page.sections[0].widgets[0].id);
  const [paletteOpen, setPaletteOpen] = useState(false);
  const [propsOpen, setPropsOpen] = useState(false);

  const allWidgets = page.sections.flatMap(s => s.widgets);
  const current = allWidgets.find(w => w.id === selWidget);

  const addWidget = (type) => {
    setPage(p => {
      const sections = p.sections.map(s => s.id === selSection ? { ...s, widgets: [...s.widgets, makeWidget(type)] } : s);
      return { ...p, sections };
    });
  };
  // after add, select the new widget
  useEffect(() => {
    const sec = page.sections.find(s => s.id === selSection);
    if (sec && sec.widgets.length) {
      const last = sec.widgets[sec.widgets.length - 1];
      // only auto-select if a brand-new id we haven't selected
    }
  }, [page]);

  const removeWidget = (id) => {
    setPage(p => ({ ...p, sections: p.sections.map(s => ({ ...s, widgets: s.widgets.filter(w => w.id !== id) })) }));
  };
  const updateProp = (k, v) => {
    setPage(p => ({ ...p, sections: p.sections.map(s => ({ ...s, widgets: s.widgets.map(w => w.id === selWidget ? { ...w, props: { ...w.props, [k]: v } } : w) })) }));
  };

  return (
    <div className={`bld ${paletteOpen ? 'pal-open' : ''} ${propsOpen ? 'props-open' : ''}`}>
      {/* top bar */}
      <div className="bld-top">
        <div className="bld-top__l">
          <button className="bld-mobtn" onClick={() => setPaletteOpen(o => !o)} aria-label="Palette"><Icon name="layers" size={17} /></button>
          <span className="bld-top__crumb mono">Baukasten / <b>{page.title}</b></span>
          <span className="chip chip--neutral chip--mono">PG-001</span>
          <span className="muted mono bld-top__saved">Auto-gespeichert · vor 8s</span>
        </div>
        <div className="bld-top__r">
          <div className="seg-tabs bld-lang"><button className="is-active">DE</button><button>EN</button></div>
          <button className="btn btn--ghost">Vorschau</button>
          <button className="btn">Veröffentlichen</button>
          <button className="bld-mobtn" onClick={() => setPropsOpen(o => !o)} aria-label="Eigenschaften"><Icon name="clipboard" size={17} /></button>
        </div>
      </div>

      <div className="bld-body">
        {/* PALETTE */}
        <aside className="bld-pal">
          <div className="bld-pal__search"><Icon name="search" size={15} /><input placeholder="Widgets filtern …" /></div>
          {WIDGET_CATALOG.map(cat => (
            <div key={cat.cat} className="bld-pal__cat" data-tint={cat.tint}>
              <span className="bld-pal__cat-h"><span className="bld-pal__dot" />{cat.cat}</span>
              {cat.items.map(it => (
                <button key={it.type} className="bld-witem" onClick={() => addWidget(it.type)} title={`„${it.name}" hinzufügen`}>
                  <span className="bld-witem__glyph">{it.glyph}</span>
                  <span>{it.name}</span>
                  <Icon name="arrowRight" size={14} className="bld-witem__add" />
                </button>
              ))}
            </div>
          ))}
        </aside>

        {/* CANVAS */}
        <section className="bld-canvas">
          <div className="bld-canvas__bar">
            <span className="muted mono">Seitenstruktur · {page.sections.length} Sektionen · {allWidgets.length} Widgets</span>
            <div className="seg-tabs bld-vp"><button className="is-active">Desktop</button><button>Mobil</button></div>
          </div>
          <div className="bld-stage">
            <div className="bld-page">
              {page.sections.map(s => (
                <div key={s.id} className={`bld-sec ${selSection === s.id ? 'is-sel' : ''}`} onClick={() => setSelSection(s.id)}>
                  <div className="bld-sec__head">
                    <span className="bld-sec__name"><Icon name="layers" size={13} /> {s.name}</span>
                    <span className="bld-sec__meta mono">{s.widgets.length} Widgets {selSection === s.id && '· Ziel'}</span>
                  </div>
                  <div className="bld-sec__widgets">
                    {s.widgets.map(w => (
                      <div key={w.id} className={`bld-w ${selWidget === w.id ? 'is-sel' : ''}`}
                        onClick={(e) => { e.stopPropagation(); setSelWidget(w.id); setSelSection(s.id); }}>
                        <div className="bld-w__bar">
                          <span className="bld-w__type mono">{WIDGET_LABEL[w.type]}</span>
                          <span className="bld-w__id mono">{w.meta.widgetId}</span>
                          <button className="bld-w__del" onClick={(e) => { e.stopPropagation(); removeWidget(w.id); }} aria-label="Entfernen"><Icon name="x" size={13} /></button>
                        </div>
                        <WidgetPreview w={w} />
                      </div>
                    ))}
                    {!s.widgets.length && <div className="bld-sec__empty mono">Leer — Widget aus der Palette hinzufügen</div>}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* PROPERTIES */}
        <aside className="bld-props">
          {current ? <BuilderProps w={current} onProp={updateProp} /> : <div className="bld-props__empty muted">Kein Widget ausgewählt</div>}
        </aside>
      </div>
    </div>
  );
}

function PField({ label, children }) {
  return <div className="pfield"><label>{label}</label><div className="pfield__c">{children}</div></div>;
}

function BuilderProps({ w, onProp }) {
  const p = w.props;
  return (
    <div className="bld-props__in">
      <div className="bld-props__hdr">
        <span className="bld-props__kind mono">Widget · {WIDGET_LABEL[w.type]}</span>
        <h2>{p.headline || p.title || p.product || p.label || WIDGET_LABEL[w.type]}</h2>
      </div>

      <div className="pgroup">
        <h6>Inhalt</h6>
        {w.type === 'text' && <>
          <PField label="Überschrift"><input value={p.headline} onChange={e => onProp('headline', e.target.value)} /></PField>
          <PField label="Text"><textarea rows={3} value={p.body} onChange={e => onProp('body', e.target.value)} /></PField>
        </>}
        {w.type === 'hero' && <>
          <PField label="Headline"><input value={p.headline} onChange={e => onProp('headline', e.target.value)} /></PField>
          <PField label="CTA-Text"><input value={p.cta} onChange={e => onProp('cta', e.target.value)} /></PField>
        </>}
        {w.type === 'hinweis' && <>
          <PField label="Ton"><select value={p.tone} onChange={e => onProp('tone', e.target.value)}><option value="info">Info</option><option value="warn">Warnung</option><option value="ok">Erfolg</option></select></PField>
          <PField label="Text"><textarea rows={2} value={p.text} onChange={e => onProp('text', e.target.value)} /></PField>
        </>}
        {(w.type === 'faq' || w.type === 'checkliste' || w.type === 'kalender') && <>
          {p.title !== undefined && <PField label="Titel"><input value={p.title} onChange={e => onProp('title', e.target.value)} /></PField>}
          <PField label="Anzahl">
            <input type="range" min="1" max="8" value={p.items ?? p.weeks} onChange={e => onProp(p.items !== undefined ? 'items' : 'weeks', +e.target.value)} />
            <span className="mono pfield__n">{p.items ?? p.weeks}</span>
          </PField>
        </>}
        {w.type === 'buttons' && <>
          <PField label="Primär-Label"><input value={p.primary} onChange={e => onProp('primary', e.target.value)} /></PField>
          <PField label="Anzahl"><input type="range" min="1" max="4" value={p.count} onChange={e => onProp('count', +e.target.value)} /><span className="mono pfield__n">{p.count}</span></PField>
        </>}
        {w.type === 'download' && <>
          <PField label="Label"><input value={p.label} onChange={e => onProp('label', e.target.value)} /></PField>
          <PField label="Datei"><input value={p.file} onChange={e => onProp('file', e.target.value)} /></PField>
        </>}
        {w.type === 'social' && <>
          <PField label="Netzwerk"><select value={p.network} onChange={e => onProp('network', e.target.value)}><option>Instagram</option><option>TikTok</option><option>YouTube</option></select></PField>
          <PField label="Handle"><input value={p.handle} onChange={e => onProp('handle', e.target.value)} /></PField>
        </>}
        {w.type === 'kurskarte' && <>
          <PField label="Titel"><input value={p.title} onChange={e => onProp('title', e.target.value)} /></PField>
          <PField label="Bereich"><input value={p.area} onChange={e => onProp('area', e.target.value)} /></PField>
        </>}
        {w.type === 'shopteaser' && <>
          <PField label="Produkt"><input value={p.product} onChange={e => onProp('product', e.target.value)} /></PField>
          <PField label="Preis"><input value={p.price} onChange={e => onProp('price', e.target.value)} /></PField>
        </>}
        {w.type === 'video' && <>
          <PField label="Anbieter"><select value={p.provider} onChange={e => onProp('provider', e.target.value)}><option>YouTube</option><option>Vimeo</option><option>MP4</option></select></PField>
          <PField label="Format"><select value={p.ratio} onChange={e => onProp('ratio', e.target.value)}><option>16:9</option><option>4:3</option><option>1:1</option></select></PField>
        </>}
      </div>

      <div className="pgroup">
        <h6>Sichtbarkeit</h6>
        <PField label="Sichtbar"><Toggle on /></PField>
        <PField label="Sprache"><select defaultValue="DE"><option>DE</option><option>EN</option><option>DE + EN</option></select></PField>
      </div>

      <div className="pgroup pgroup--meta">
        <h6><Icon name="info" size={12} /> Automatische Metadaten</h6>
        {[['widgetId', w.meta.widgetId], ['pageId', w.meta.pageId], ['language', w.meta.language], ['version', 'v' + w.meta.version], ['createdBy', w.meta.createdBy], ['updatedAt', w.meta.updatedAt], ['trackingKey', w.meta.trackingKey]].map(([k, v]) => (
          <div key={k} className="meta-row"><span className="meta-row__k mono">{k}</span><span className="meta-row__v mono">{v}</span></div>
        ))}
      </div>
    </div>
  );
}

function Toggle({ on }) {
  const [v, setV] = useState(!!on);
  return <button className={`tg-pill ${v ? 'on' : ''}`} onClick={() => setV(!v)} aria-pressed={v}><span /></button>;
}

Object.assign(window, { AdminBuilder });
