// Rezept-Detail-Seite — universell.
// Quellen:
//   * window.__RECIPE__ (synchron gesetzt durch /api/rezept.js — z.B. wenn
//     Vercel die Seite server-rendert) → direkt verwenden.
//   * Slug aus window.location.pathname (z.B. /rezepte/khoresh-bademjan)
//     UND nicht "ghormeh-sabzi-tehrani" → fetch via /api/recipes/{slug}.
//   * Fallback: i18n.jsx (Ghormeh-Sabzi-Hardcode).
// In allen Faellen rendert die exakt gleiche Komponente mit Site-Header/-Footer.

function rdResolveLang(recipe, langCode) {
  if (!recipe || !recipe.translations) return null;
  return recipe.translations[langCode] || recipe.translations.de || null;
}

function rdSlugFromPath() {
  try {
    const m = (window.location.pathname || '').match(/^\/rezepte\/([^/?#]+)/);
    return m ? decodeURIComponent(m[1]) : null;
  } catch (e) { return null; }
}

function RezeptDetailPage({ recipe: recipeProp }) {
  const { t, lang } = useT();
  const initialRecipe = recipeProp || (typeof window !== 'undefined' ? window.__RECIPE__ : null) || null;
  const [recipe, setRecipe] = React.useState(initialRecipe);
  const [loading, setLoading] = React.useState(!initialRecipe);
  const [error, setError] = React.useState(null);
  const [related, setRelated] = React.useState([]);

  // Cross-Linking: weitere Rezepte aus dem KV-Index laden, aktuelles ausschliessen.
  React.useEffect(() => {
    let alive = true;
    fetch('/api/recipes/list', { headers: { Accept: 'application/json' } })
      .then((r) => r.ok ? r.json() : null)
      .then((json) => {
        if (!alive || !json || !Array.isArray(json.items)) return;
        const currentSlug = (recipe && recipe.slug) || rdSlugFromPath();
        const others = json.items.filter((it) => it && it.slug && it.slug !== currentSlug).slice(0, 4);
        setRelated(others);
      })
      .catch(() => {});
    return () => { alive = false; };
  }, [recipe]);

  // Fetch wenn kein Server-injizierter Recipe und Slug != "ghormeh-sabzi-tehrani".
  React.useEffect(() => {
    if (recipeProp) return;
    if (recipe) return; // schon gesetzt
    const slug = rdSlugFromPath();
    if (!slug || slug === 'ghormeh-sabzi-tehrani') {
      setLoading(false);
      return;
    }
    let alive = true;
    fetch(`/api/recipes/${encodeURIComponent(slug)}`, { headers: { Accept: 'application/json' } })
      .then((r) => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
      .then((json) => {
        if (!alive) return;
        if (json && json.ok && json.recipe) setRecipe(json.recipe);
        else setError('Rezept nicht gefunden.');
      })
      .catch((err) => { if (alive) setError(err.message || 'Ladefehler'); })
      .finally(() => { if (alive) setLoading(false); });
    return () => { alive = false; };
  }, [recipeProp, recipe]);

  // Daten ableiten — entweder aus fetched recipe oder aus i18n.
  const langData = rdResolveLang(recipe, lang);
  const useRemote = !!langData;

  const name           = useRemote ? langData.name           : t('rezept.name');
  const eyebrow        = useRemote ? (langData.eyebrow || t('rezept.eyebrow')) : t('rezept.eyebrow');
  const desc           = useRemote ? langData.desc           : t('rezept.desc');
  const ingredients    = useRemote ? (langData.ingredients || []) : (t('rezept.ingredients') || []);
  const ingredientsTitle = useRemote ? langData.ingredients_title : t('rezept.ingredientsTitle');
  const steps          = useRemote ? (langData.steps || [])  : (t('rezept.steps') || []);
  const stepsTitle     = useRemote
    ? (lang === 'tr' ? 'Hazırlanışı' : lang === 'fa' ? 'دستور پخت' : lang === 'ar' ? 'طريقة التحضير' : 'Zubereitung')
    : t('rezept.detail.stepsTitle');
  const tipsTitle      = useRemote ? langData.tips_title     : t('rezept.detail.tipsTitle');
  const tips           = useRemote ? (langData.tips || [])   : (t('rezept.detail.tipsList') || []);
  const servingTitle   = useRemote ? langData.serving_title  : t('rezept.detail.servingTitle');
  const servingIntro   = useRemote ? langData.serving_intro  : t('rezept.detail.servingIntro');
  const servingGroups  = useRemote ? (langData.serving_groups || []) : (t('rezept.detail.servingGroups') || []);
  const timeLabel      = useRemote ? (langData.time_label || t('rezept.time')) : t('rezept.time');
  const timeValue      = useRemote ? langData.time_value     : t('rezept.timeValue');
  const portionsLabel  = useRemote ? (langData.portions_label || t('rezept.portions')) : t('rezept.portions');
  const portions       = useRemote ? (langData.portions || '4') : '4';
  const levelLabel     = useRemote ? (langData.level_label || t('rezept.level')) : t('rezept.level');
  const level          = useRemote ? (langData.level || '★★☆') : '★★☆';
  const stamp          = useRemote ? (langData.stamp || t('rezept.detail.badge')) : t('rezept.detail.badge');
  const imgSrc         = useRemote
    ? (recipe.image_url || 'uploads/rezept-ghormeh-sabzi.jpg')
    : 'uploads/rezept-ghormeh-sabzi.jpg';

  React.useEffect(() => {
    if (name) document.title = `${name} — ${t('site.name')}`;
  }, [name, t]);

  return (
    <React.Fragment>
      <Header/>

      {loading && (
        <main id="main">
          <section style={{ background:'var(--paper)', minHeight:'40vh' }}>
            <div className="container" style={{ textAlign:'center', padding:'60px 0' }}>
              <div className="eyebrow">Rezept wird geladen…</div>
            </div>
          </section>
        </main>
      )}

      {!loading && error && (
        <main id="main">
          <section style={{ background:'var(--paper)', minHeight:'40vh' }}>
            <div className="container" style={{ textAlign:'center', padding:'60px 0' }}>
              <h1 style={{ marginBottom: 16 }}>Rezept nicht gefunden</h1>
              <p style={{ color:'var(--ink-2)' }}>{error}</p>
              <p style={{ marginTop: 24 }}>
                <a href="/rezepte" className="btn ghost">{t('rezept.archive')}</a>
                {' '}
                <a href="/" className="btn gold">Zur Startseite</a>
              </p>
            </div>
          </section>
        </main>
      )}

      {!loading && !error && (
      <main id="main">
        {/* Hero — Bild, Titel, Beschreibung, Eckdaten */}
        <section style={{ background:'var(--paper)' }}>
          <div className="container">
            <a href="/#rezept" style={{ fontFamily:'var(--font-mono)', fontSize:12, letterSpacing:'.08em', color:'var(--ink-2)', textTransform:'uppercase', display:'inline-block', marginBottom:32 }}>
              {useRemote ? '← Zurück zur Startseite' : t('rezept.detail.back')}
            </a>

            <div className="rd-hero">
              <div style={{ position:'relative' }}>
                <ResponsiveImg
                  src={imgSrc}
                  alt={name}
                  sizes="(min-width: 900px) 45vw, 100vw"
                  loading="eager"
                  fetchpriority="high"
                  style={{ width:'100%', aspectRatio:'4/5', objectFit:'cover', borderRadius:6, display:'block', border:'1px solid var(--line)' }} />
                <div style={{ position:'absolute', top:-18, insetInlineStart:-18, background:'var(--brick)', color:'var(--paper)', padding:'10px 18px', borderRadius:999, fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.14em', textTransform:'uppercase', transform:'rotate(-4deg)', boxShadow:'0 8px 24px rgba(0,0,0,.18)' }}>
                  {stamp}
                </div>
              </div>

              <div>
                <span className="eyebrow">{eyebrow}</span>
                <h1 style={{ marginTop:10, fontSize:'clamp(40px,5vw,72px)', lineHeight:1 }}>{name}</h1>
                <p style={{ marginTop:20, fontSize:18, color:'var(--ink-2)', maxWidth:560 }}>{desc}</p>

                <div style={{ marginTop:32, display:'flex', gap:24, flexWrap:'wrap', fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'.06em' }}>
                  <div style={{ background:'var(--paper)', border:'1px solid var(--line)', padding:'14px 20px', borderRadius:6 }}>
                    <div style={{ color:'var(--gold-deep)' }}>{timeLabel}</div>
                    <div style={{ fontFamily:'var(--font-display)', fontSize:22, marginTop:4 }}>{timeValue}</div>
                  </div>
                  <div style={{ background:'var(--paper)', border:'1px solid var(--line)', padding:'14px 20px', borderRadius:6 }}>
                    <div style={{ color:'var(--gold-deep)' }}>{portionsLabel}</div>
                    <div style={{ fontFamily:'var(--font-display)', fontSize:22, marginTop:4 }}>{portions}</div>
                  </div>
                  <div style={{ background:'var(--paper)', border:'1px solid var(--line)', padding:'14px 20px', borderRadius:6 }}>
                    <div style={{ color:'var(--gold-deep)' }}>{levelLabel}</div>
                    <div style={{ fontFamily:'var(--font-display)', fontSize:22, marginTop:4 }}>{level}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Zutaten */}
        <section style={{ background:'var(--bg)' }}>
          <div className="container" style={{ maxWidth:880 }}>
            <h2>{ingredientsTitle}</h2>
            <ul className="rd-ing">
              {ingredients.map((ing, i) => (
                <li key={i} style={{ display:'flex', flexWrap:'wrap', alignItems:'baseline', columnGap:16, rowGap:2, paddingBottom:12, borderBottom:'1px dashed var(--line)' }}>
                  <span style={{ fontFamily:'var(--font-display)', fontSize:18, flex:'1 1 60%', minWidth:0 }}>{ing.t}</span>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:12, color:'var(--ink-2)', whiteSpace:'nowrap', marginInlineStart:'auto', textAlign:'end' }}>{ing.amt}</span>
                </li>
              ))}
            </ul>
          </div>
        </section>

        {/* Zubereitung */}
        <section style={{ background:'var(--paper)' }}>
          <div className="container" style={{ maxWidth:880 }}>
            <h2>{stepsTitle}</h2>
            <ol style={{ marginTop:32, padding:0, listStyle:'none', display:'grid', gap:24 }}>
              {steps.map((s, i) => (
                <li key={i} style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:24, alignItems:'baseline', padding:'24px 28px', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:8 }}>
                  <span style={{ fontFamily:'var(--font-display)', fontSize:48, fontWeight:800, color:'var(--brick)', lineHeight:1 }}>{String(i+1).padStart(2,'0')}</span>
                  <span style={{ fontSize:17, color:'var(--ink-2)', lineHeight:1.65 }}>{s}</span>
                </li>
              ))}
            </ol>
          </div>
        </section>

        {/* Tipps */}
        {tips.length > 0 && (
          <section style={{ background:'var(--bg)' }}>
            <div className="container" style={{ maxWidth:880 }}>
              <h2>{tipsTitle}</h2>
              <ul style={{ listStyle:'none', margin:'32px 0 0', padding:0, display:'grid', gap:16 }}>
                {tips.map((tip, i) => (
                  <li key={i} style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:18, alignItems:'baseline', padding:'18px 22px', background:'var(--paper)', border:'1px solid var(--line)', borderRadius:6 }}>
                    <span style={{ fontFamily:'var(--font-mono)', fontSize:12, color:'var(--brick)', letterSpacing:'.06em', minWidth:22 }}>{String(i+1).padStart(2,'0')}</span>
                    <span style={{ fontSize:16, color:'var(--ink-2)', lineHeight:1.65 }}>{tip}</span>
                  </li>
                ))}
              </ul>
            </div>
          </section>
        )}

        {/* Beilagen & Servieren */}
        {servingGroups.length > 0 && (
          <section style={{ background:'var(--paper)' }}>
            <div className="container">
              <h2>{servingTitle}</h2>
              <p style={{ marginTop:16, fontSize:17, color:'var(--ink-2)', maxWidth:680 }}>{servingIntro}</p>
              <div style={{ marginTop:36, display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(min(100%, 240px), 1fr))', gap:20 }}>
                {servingGroups.map((g, i) => (
                  <div key={i} style={{ padding:'24px 26px', background:'var(--bg)', border:'1px solid var(--line)', borderRadius:8 }}>
                    <h3 style={{ fontSize:20 }}>{g.t}</h3>
                    <p style={{ marginTop:10, fontSize:15, color:'var(--ink-2)', lineHeight:1.65 }}>{g.d}</p>
                  </div>
                ))}
              </div>
            </div>
          </section>
        )}

        {/* Cross-Linking — Mehr Rezepte aus dem Markt */}
        {related.length > 0 && (
          <section style={{ background:'var(--bg)' }}>
            <div className="container">
              <span className="eyebrow">Mehr aus der Rezept-Sammlung</span>
              <h2 style={{ marginTop:8 }}>Weitere Rezepte aus dem Markt</h2>
              <div className="rd-related" style={{ marginTop:24, display:'grid', gap:14, gridTemplateColumns:'repeat(auto-fit, minmax(min(100%, 180px), 1fr))' }}>
                {related.map((r) => (
                  <a key={r.slug} href={`/rezepte/${encodeURIComponent(r.slug)}`}
                    style={{ display:'block', background:'var(--paper)', border:'1px solid var(--line)', borderRadius:6, overflow:'hidden', color:'inherit', transition:'transform .15s ease, box-shadow .15s ease' }}
                    onMouseEnter={(e) => { e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='0 8px 22px rgba(0,0,0,.07)'; }}
                    onMouseLeave={(e) => { e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow=''; }}>
                    <div style={{ aspectRatio:'1/1', overflow:'hidden', background:'var(--bg-2)' }}>
                      <ResponsiveImg src={r.image_url || 'uploads/rezept-ghormeh-sabzi.jpg'} alt={r.name_de || r.slug} sizes="(min-width: 900px) 20vw, (min-width: 600px) 33vw, 50vw" style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }}/>
                    </div>
                    <div style={{ padding:'12px 14px 16px' }}>
                      <h3 style={{ margin:0, fontSize:18, lineHeight:1.25, fontWeight:700 }}>{r.name_de || r.slug}</h3>
                    </div>
                  </a>
                ))}
              </div>
              <div style={{ marginTop:24, textAlign:'center' }}>
                <a href="/rezepte" className="btn ghost">{t('rezept.archiveView')}</a>
              </div>
            </div>
          </section>
        )}

        {/* CTA — zurück zu Angeboten */}
        <section style={{ background:'var(--ink)', color:'var(--paper)' }}>
          <div className="container" style={{ textAlign:'center' }}>
            <div style={{ display:'flex', gap:14, flexWrap:'wrap', justifyContent:'center' }}>
              <a href="/#angebote" className="btn gold"><Icon name="tray" size={16}/> {useRemote ? 'Zu den Wochenangeboten' : t('rezept.cta')}</a>
              <a href="/rezepte" className="btn ghost" style={{ color:'var(--paper)', borderColor:'var(--paper)' }}>{t('rezept.archive')}</a>
              <a href="/#rezept" className="btn ghost" style={{ color:'var(--paper)', borderColor:'var(--paper)' }}>{useRemote ? '← Zur Startseite' : t('rezept.detail.back')}</a>
            </div>
          </div>
        </section>
      </main>
      )}

      <Footer/>
      <CookieBanner/>
      <LegalModal/>

      <style>{`
        .rd-hero{ display:grid; grid-template-columns:1fr; gap:28px; align-items:center; }
        .rd-ing{ list-style:none; margin:24px 0 0; padding:0;
          display:grid; grid-template-columns:1fr; gap:12px 24px; }
        @media (min-width: 600px){
          .rd-hero{ gap:40px; }
          .rd-ing{ grid-template-columns:1fr 1fr; gap:14px 32px; margin-top:32px; }
        }
        @media (min-width: 900px){
          .rd-hero{ grid-template-columns:.95fr 1.05fr; gap:56px; }
        }
      `}</style>
    </React.Fragment>
  );
}

function RezeptDetailApp() {
  return (
    <I18nProvider>
      <RezeptDetailPage/>
    </I18nProvider>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<RezeptDetailApp/>);
