---
import Admin from '../../../layouts/Admin.astro';
import { getProductById, createProduct, updateProduct, deleteProduct } from '../../../lib/store.js';
const { id } = Astro.params;
const isNew = id === 'neu';
const slugify = (s)=>s.toLowerCase().replace(/ä/g,'ae').replace(/ö/g,'oe').replace(/ü/g,'ue').replace(/ß/g,'ss').replace(/&/g,'und').replace(/[^a-z0-9]+/g,'-').replace(/(^-|-$)/g,'');
const lines = (v)=>String(v||'').split(/[\n,]/).map(x=>x.trim()).filter(Boolean);

if (Astro.request.method === 'POST') {
  const f = await Astro.request.formData();
  if (f.get('_action') === 'delete') { await deleteProduct(id); return Astro.redirect('/admin/produkte?ok=del'); }
  const name = String(f.get('name')||'').trim();
  const priceCents = Math.round(parseFloat(String(f.get('price')||'0').replace(',','.')) * 100) || 0;
  const data = {
    name, shortName: String(f.get('shortName')||name).trim() || name,
    slug: String(f.get('slug')||'').trim() || slugify(name),
    desc: String(f.get('desc')||'').trim(), category: String(f.get('category')||'').trim(),
    productType: 'physical', priceCents,
    stock: String(f.get('stock')||'').trim()==='' ? null : parseInt(String(f.get('stock'))),
    sizes: lines(f.get('sizes')).length ? lines(f.get('sizes')) : ['One Size'],
    images: lines(f.get('images')), cardImage: String(f.get('cardImage')||'').trim(),
    freigestellt: String(f.get('freigestellt')||'').trim(), badge: String(f.get('badge')||'').trim(),
    material: String(f.get('material')||'').trim(), features: lines(f.get('features')),
    featured: !!f.get('featured'), sort: parseInt(String(f.get('sort')||'99'))||99,
  };
  if (isNew) await createProduct(data); else await updateProduct(id, data);
  return Astro.redirect('/admin/produkte?ok=save');
}
const p = isNew ? {} : (await getProductById(id)) || {};
if (!isNew && !p.id) return Astro.redirect('/admin/produkte');
const priceVal = p.priceCents != null ? (p.priceCents/100).toFixed(2).replace('.',',') : '';
---
<Admin title={isNew ? 'Neues Produkt' : p.name} active="produkte" crumbs={[{label:'Produkte',href:'/admin/produkte'},{label:isNew?'Neu':p.shortName}]}>
  <div slot="actions" style="display:flex;gap:8px">
    {!isNew && (
      <form method="POST" onsubmit="return confirm('Produkt wirklich löschen?')"><input type="hidden" name="_action" value="delete"/>
        <button class="s-btn s-btn-danger" type="submit">Löschen</button></form>
    )}
    <button form="prodform" class="s-btn s-btn-primary" type="submit">Speichern</button>
  </div>

  <form id="prodform" method="POST" class="s-two-col">
    <div class="s-stack">
      <div class="s-card s-card-pad">
        <div class="s-field full"><label class="s-label">Titel</label><input class="s-input" name="name" value={p.name||''} required/></div>
        <div class="s-field full"><label class="s-label">Kurzname (für Karten)</label><input class="s-input" name="shortName" value={p.shortName||''}/></div>
        <div class="s-field full"><label class="s-label">Beschreibung</label><textarea class="s-textarea" name="desc" rows="4">{p.desc||''}</textarea></div>
      </div>
      <div class="s-card s-card-pad">
        <p class="s-section-title">Medien</p>
        <div class="s-field full" style="margin-top:10px"><label class="s-label">Karten-Bild (URL)</label><input class="s-input" name="cardImage" value={p.cardImage||''} placeholder="/product-images/…"/></div>
        <div class="s-field full"><label class="s-label">Freigestelltes Bild (optional)</label><input class="s-input" name="freigestellt" value={p.freigestellt||''}/></div>
        <div class="s-field full"><label class="s-label">Galerie-Bilder (eine URL pro Zeile)</label><textarea class="s-textarea" name="images" rows="3">{(p.images||[]).join('\n')}</textarea></div>
      </div>
      <div class="s-card s-card-pad">
        <p class="s-section-title">Varianten & Details</p>
        <div class="s-form-grid" style="margin-top:10px">
          <div class="s-field"><label class="s-label">Größen (Komma)</label><input class="s-input" name="sizes" value={(p.sizes||['One Size']).join(', ')}/></div>
          <div class="s-field"><label class="s-label">Material</label><input class="s-input" name="material" value={p.material||''}/></div>
        </div>
        <div class="s-field full"><label class="s-label">Features (eine pro Zeile)</label><textarea class="s-textarea" name="features" rows="3">{(p.features||[]).join('\n')}</textarea></div>
      </div>
    </div>

    <div class="s-stack">
      <div class="s-card s-card-pad">
        <p class="s-section-title">Status</p>
        <label class="s-check" style="margin-top:10px"><input type="checkbox" name="featured" checked={!!p.featured}/> Als „Featured" markieren</label>
      </div>
      <div class="s-card s-card-pad">
        <p class="s-section-title">Preis & Bestand</p>
        <div class="s-field" style="margin-top:10px"><label class="s-label">Preis (EUR, brutto)</label><input class="s-input" name="price" value={priceVal} inputmode="decimal" placeholder="49,99" required/></div>
        <div class="s-field"><label class="s-label">Bestand (Stück)</label><input class="s-input" name="stock" value={p.stock??''} type="number" placeholder="leer = ohne Tracking"/></div>
      </div>
      <div class="s-card s-card-pad">
        <p class="s-section-title">Organisation</p>
        <div class="s-field" style="margin-top:10px"><label class="s-label">Kategorie</label>
          <input class="s-input" name="category" value={p.category||''} list="cats"/>
          <datalist id="cats"><option>Hoodie</option><option>T-Shirt</option><option>Cap</option><option>Tasche</option><option>Digital</option></datalist></div>
        <div class="s-field"><label class="s-label">Badge</label><input class="s-input" name="badge" value={p.badge||''} placeholder="z. B. Neu, Bio, Bestseller"/></div>
        <div class="s-form-grid">
          <div class="s-field"><label class="s-label">Slug</label><input class="s-input" name="slug" value={p.slug||''} placeholder="automatisch"/></div>
          <div class="s-field"><label class="s-label">Sortierung</label><input class="s-input" name="sort" value={p.sort??99} type="number"/></div>
        </div>
      </div>
    </div>
  </form>
</Admin>
