// prototype.jsx — Zapfbräu app router & host

const { useState, useEffect } = React;

// Update index.html script order — this loads after screens & screens2
// All screens are on window from those files.

function App() {
  const [tweaks, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);
  const palette = PALETTES[tweaks.palette] || PALETTES.wald;

  const [route, setRoute] = useState('home');
  const [stamps, setStamps] = useState(tweaks.stampCount);
  const [showQR, setShowQR] = useState(false);
  const [appData, setAppData] = useState(() => JSON.parse(JSON.stringify(window.DEFAULT_APP_DATA)));
  const [inApp, setInApp] = useState(null); // { url, title }

  const openInApp = (url, title) => setInApp({ url, title });

  // Keep stamps in sync with tweak slider
  useEffect(() => { setStamps(tweaks.stampCount); }, [tweaks.stampCount]);

  const goto = (r) => { setRoute(r); window.scrollTo(0, 0); };

  let screen;
  switch (route) {
    case 'home':  screen = <HomeScreen palette={palette} tweaks={tweaks} goto={goto} stamps={stamps} appData={appData} openInApp={openInApp}/>; break;
    case 'menu':  screen = <MenuScreen palette={palette} appData={appData}/>; break;
    case 'stamp': screen = <StampPassScreen palette={palette} tweaks={tweaks} stamps={stamps} setStamps={setStamps} openQR={()=>setShowQR(true)}/>; break;
    case 'book':  screen = <BookScreen palette={palette} onComplete={()=>goto('bookie')}/>; break;
    case 'bookie': screen = <BookHub palette={palette} goto={goto}/>; break;
    case 'rooms': screen = <RoomsScreen palette={palette}/>; break;
    case 'info':  screen = <InfoScreen palette={palette} appData={appData} openInApp={openInApp} goto={goto}/>; break;
    case 'faq':   screen = <FaqScreen palette={palette}/>; break;
    case 'beer':  screen = <BeerScreen palette={palette}/>; break;
    default:      screen = <HomeScreen palette={palette} tweaks={tweaks} goto={goto} stamps={stamps}/>;
  }

  // Map secondary routes (rooms, beer) onto the bottom-nav 'book' / 'info' for highlighting
  const navHighlight = (route === 'rooms' || route === 'book' || route === 'bookie') ? 'bookie'
                     : (route === 'beer' || route === 'info' || route === 'faq') ? 'info'
                     : route;

  return (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap: 40, flexWrap: 'wrap' }}>
      {/* Phone */}
      <div style={{
        width: 380, height: 820, borderRadius: 44,
        background: '#0d0c0a',
        padding: 8,
        boxShadow: `0 40px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.08), inset 0 0 0 1px rgba(255,255,255,0.04)`,
        position: 'relative',
      }}>
        <div style={{
          width: '100%', height: '100%', borderRadius: 38,
          overflow: 'hidden', background: palette.cream,
          display:'flex', flexDirection:'column', position:'relative',
        }}>
          <StatusBar palette={palette} light={route === 'home'}/>
          {/* Back chevron header for sub-routes */}
          {(route === 'rooms' || route === 'beer' || route === 'bookie' || route === 'faq') && (
            <SubHeader palette={palette}
              title={route==='rooms'?'Zimmer':route==='beer'?'Biere':route==='faq'?'FAQ':'Buchen'}
              onBack={() => goto(route==='rooms'?'bookie':route==='beer'?'info':route==='faq'?'info':'home')}/>
          )}
          <div style={{ flex: 1, overflow: 'auto', position:'relative' }}>
            {screen}
            {showQR && route === 'stamp' && <CodeModal palette={palette} onClose={()=>setShowQR(false)} onStamp={(delta)=>setStamps(s=>Math.max(0,Math.min(20,s+delta)))}/>}
            {inApp && <InAppBrowser url={inApp.url} title={inApp.title} palette={palette} onClose={()=>setInApp(null)}/>}
          </div>
          <BottomNav current={navHighlight} onNav={goto} palette={palette}/>
          {/* Gesture pill */}
          <div style={{ height: 18, display:'flex', alignItems:'center', justifyContent:'center', background: palette.paper }}>
            <div style={{ width: 100, height: 4, borderRadius: 2, background: palette.ink, opacity: 0.3 }}/>
          </div>
        </div>
      </div>

      {/* Side panel: design notes & quick links */}
      <SideNotes palette={palette} stamps={stamps} setStamps={setStamps} goto={goto} route={route} appData={appData} setAppData={setAppData}/>

      {/* Tweaks */}
      <ZapfTweaks tweaks={tweaks} setTweak={setTweak}/>

      <style>{`
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        ::-webkit-scrollbar { width: 0; height: 0; }
        button:active { transform: scale(0.97); }
        button { transition: transform 0.1s, background 0.2s, color 0.2s; }
      `}</style>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Sub-page header (back button)
// ─────────────────────────────────────────────────────────────
const SubHeader = ({ title, onBack, palette }) => (
  <div style={{
    display:'flex', alignItems:'center', gap: 14, padding: '10px 14px',
    background: palette.cream, borderBottom: `1px solid ${palette.green}10`,
  }}>
    <button onClick={onBack} style={{
      width: 38, height: 38, borderRadius: 19, background: palette.green + '12',
      border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
    }}>
      <Icon name="arrowLeft" size={18} color={palette.green}/>
    </button>
    <div style={{ fontFamily:'"DM Serif Display", serif', fontSize: 20, color: palette.ink }}>{title}</div>
  </div>
);

// ─────────────────────────────────────────────────────────────
// Side notes panel
// ─────────────────────────────────────────────────────────────
const SideNotes = ({ palette, stamps, setStamps, goto, route, appData, setAppData }) => {
  const [tab, setTab] = React.useState('notizen');
  const [adminPin, setAdminPin] = React.useState('');
  const [adminError, setAdminError] = React.useState('');
  const [unlocked, setUnlocked] = React.useState(() => sessionStorage.getItem('zapf-admin') === '1');

  const tryUnlock = () => {
    if (adminPin === '1883') {
      setUnlocked(true);
      sessionStorage.setItem('zapf-admin', '1');
      setAdminError('');
    } else {
      setAdminError('Falscher Code.');
      setAdminPin('');
    }
  };

  return (
    <div style={{ width: 320, color: '#f4efe6', fontFamily: 'Manrope, sans-serif' }}>

      {/* Tab bar */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 18 }}>
        {[['notizen','Notizen'],['bearbeiten','Bearbeiten']].map(([k, label]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            flex: 1, padding: '9px 0', borderRadius: 10, cursor: 'pointer', border: 'none',
            background: tab === k ? '#c97d26' : 'rgba(244,239,230,0.08)',
            color: tab === k ? '#1f2a1f' : '#f4efe6',
            fontFamily: 'Manrope', fontSize: 12.5, fontWeight: tab === k ? 700 : 500,
          }}>{label}</button>
        ))}
      </div>

      {tab === 'notizen' && (
        <>
          <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase', color:'#c97d26', marginBottom: 10 }}>
            ⌁ Designnotizen
          </div>
          <h2 style={{ fontFamily:'"DM Serif Display", serif', fontSize: 28, lineHeight: 1.05, margin: '0 0 14px' }}>
            Zapfbräu — eine kleine App für ein traditionsreiches Haus
          </h2>
          <p style={{ fontSize: 13.5, lineHeight: 1.55, opacity: 0.78, margin: 0 }}>
                Erste Version. Fokus: Information, Tisch‑Reservierung & ein <i style={{color:'#d18a3a'}}>Stempelpass</i>, der wirkt wie ein Bierdeckel. Drei Belohnungs-Stufen: <b>5 → Hausbier</b>, <b>10 → Cocktail nach Wahl</b>, <b>20 → günstigstes Essen frei</b>.
          </p>

          <div style={{ marginTop: 22, paddingTop: 22, borderTop: '1px solid rgba(244,239,230,0.12)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10.5, letterSpacing:'0.18em', textTransform:'uppercase', opacity: 0.6, marginBottom: 10 }}>
              Schnellsprung
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 6 }}>
              {[
                ['home','Heim'],['menu','Speisekarte'],['stamp','Stempelpass'],
                ['bookie','Buchen'],['rooms','Zimmer'],['beer','Biere'],
                ['info','Info & Anfahrt'],['faq','FAQ'],
              ].map(([r, label]) => (
                <button key={r} onClick={()=>goto(r)} style={{
                  padding:'8px 10px', textAlign:'left', cursor:'pointer',
                  background: route===r ? '#c97d26' : 'rgba(244,239,230,0.06)',
                  color: route===r ? '#1f2a1f' : '#f4efe6',
                  border:'1px solid rgba(244,239,230,0.1)', borderRadius: 8,
                  fontFamily:'Manrope', fontSize: 12, fontWeight: route===r ? 700 : 500,
                }}>{label}</button>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 22, paddingTop: 22, borderTop: '1px solid rgba(244,239,230,0.12)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10.5, letterSpacing:'0.18em', textTransform:'uppercase', opacity: 0.6, marginBottom: 10 }}>
              Stempel demo
            </div>
            <div style={{ display:'flex', gap: 6, alignItems:'center' }}>
              <button onClick={()=>setStamps(Math.max(0, stamps-1))} style={btnDark}>–</button>
              <div style={{ flex: 1, textAlign:'center', fontFamily:'"DM Serif Display", serif', fontSize: 24 }}>{stamps} <span style={{opacity:0.4, fontSize: 14}}>/ 20</span></div>
              <button onClick={()=>setStamps(Math.min(20, stamps+1))} style={btnDark}>+</button>
            </div>
          </div>

          <div style={{ marginTop: 22, paddingTop: 22, borderTop: '1px solid rgba(244,239,230,0.12)', fontSize: 11.5, opacity: 0.55, lineHeight: 1.55 }}>
            <b style={{ color: '#c97d26' }}>Nächste Schritte:</b><br/>
            • Englische Version umschaltbar<br/>
            • Hotel-Buchungsflow vertiefen<br/>
            • Push für „Heut frisch g'zapft"<br/>
            • Stempel-Backend (QR-Signatur)
          </div>
        </>
      )}

      {tab === 'bearbeiten' && !unlocked && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10.5, letterSpacing:'0.18em', textTransform:'uppercase', color:'#c97d26' }}>⌁ Admin-Bereich</div>
          <div style={{ fontFamily:'"DM Serif Display", serif', fontSize: 20, color:'#f4efe6', lineHeight: 1.1 }}>Bitte PIN eingeben</div>
          <input
            type="password" inputMode="numeric" maxLength={4}
            value={adminPin}
            onChange={e => { setAdminPin(e.target.value.replace(/\D/g,'')); setAdminError(''); }}
            onKeyDown={e => e.key === 'Enter' && tryUnlock()}
            placeholder="_ _ _ _"
            style={{ textAlign:'center', fontSize: 28, letterSpacing: 10, padding: '12px 0',
              background:'rgba(244,239,230,0.08)', border:`1px solid ${adminError ? '#ef4444' : 'rgba(244,239,230,0.2)'}`,
              borderRadius: 10, color:'#f4efe6', fontFamily:'"DM Serif Display", serif', outline:'none' }}
          />
          {adminError && <div style={{ fontSize: 11.5, color:'#ef4444', textAlign:'center' }}>{adminError}</div>}
          <button onClick={tryUnlock} style={{
            padding:'12px', borderRadius:10, border:'none', cursor:'pointer',
            background: adminPin.length===4 ? '#c97d26' : 'rgba(244,239,230,0.1)',
            color: '#f4efe6', fontFamily:'Manrope', fontWeight:700, fontSize:13,
          }}>Entsperren</button>
        </div>
      )}

      {tab === 'bearbeiten' && unlocked && (
        <ContentEditor appData={appData} setAppData={setAppData} />
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────
// Content Editor — inline editable fields for app data
// ─────────────────────────────────────────────────────────────
const ContentEditor = ({ appData, setAppData }) => {
  const [section, setSection] = React.useState('hours');

  const updateContact = (key, val) =>
    setAppData(d => ({ ...d, contact: { ...d.contact, [key]: val } }));

  const updateHourTime = (rowIdx, timeIdx, val) =>
    setAppData(d => {
      const hours = d.hours.map((h, i) => {
        if (i !== rowIdx) return h;
        const times = h.times.map((t, ti) => ti === timeIdx ? val : t);
        return { ...h, times };
      });
      return { ...d, hours };
    });

  const addTimeSlot = (rowIdx) =>
    setAppData(d => {
      const hours = d.hours.map((h, i) =>
        i === rowIdx ? { ...h, times: [...h.times, ''] } : h
      );
      return { ...d, hours };
    });

  const removeTimeSlot = (rowIdx, timeIdx) =>
    setAppData(d => {
      const hours = d.hours.map((h, i) => {
        if (i !== rowIdx) return h;
        const times = h.times.filter((_, ti) => ti !== timeIdx);
        return { ...h, times: times.length ? times : ['—'] };
      });
      return { ...d, hours };
    });

  const toggleClosed = (rowIdx) =>
    setAppData(d => {
      const hours = d.hours.map((h, i) =>
        i === rowIdx ? { ...h, closed: !h.closed } : h
      );
      return { ...d, hours };
    });

  const sectionTabs = [['hours','Zeiten'],['sonder','Sonder'],['contact','Kontakt'],['texts','Texte'],['woche','Wochenkarte'],['aktuell','Aktuell'],['ampel','Ampel']];

  return (
    <div>
      <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10.5, letterSpacing:'0.18em', textTransform:'uppercase', color:'#c97d26', marginBottom: 14 }}>
        ⌁ Inhalt korrigieren
      </div>
      <p style={{ fontSize: 12, lineHeight: 1.5, opacity: 0.65, margin: '0 0 16px' }}>
        Änderungen werden sofort im Telefon angezeigt. Navigiere zu „Haus" um die Öffnungszeiten zu sehen.
      </p>

      {/* Sub-tabs */}
      <div style={{ display:'flex', gap: 4, marginBottom: 18 }}>
        {sectionTabs.map(([k, label]) => (
          <button key={k} onClick={() => setSection(k)} style={{
            flex: 1, padding: '8px 0', borderRadius: 8, cursor:'pointer', border:'none',
            background: section === k ? 'rgba(244,239,230,0.18)' : 'rgba(244,239,230,0.06)',
            color: '#f4efe6', fontFamily:'Manrope', fontSize: 12, fontWeight: section === k ? 700 : 400,
            borderBottom: section === k ? '2px solid #c97d26' : '2px solid transparent',
          }}>{label}</button>
        ))}
      </div>

      {section === 'sonder' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          <div style={{ fontSize:11.5, opacity:0.65, lineHeight:1.5 }}>Betriebsruhe und Feiertage werden auf der Haus-Seite angezeigt. Leere Felder werden ausgeblendet.</div>

          {/* Betriebsruhe */}
          <div style={{ background:'rgba(244,239,230,0.06)', borderRadius:10, padding:12, border:'1px solid rgba(244,239,230,0.1)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity:0.6, marginBottom:10 }}>Betriebsruhe</div>
            {(appData.sonderzeiten?.betriebsruhe || []).map((b, i) => (
              <div key={i} style={{ display:'flex', gap:6, marginBottom:6, alignItems:'center' }}>
                <input value={b.von} onChange={e => { const u=[...(appData.sonderzeiten.betriebsruhe)]; u[i]={...u[i],von:e.target.value}; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,betriebsruhe:u}})); }} placeholder="von TT.MM.JJ"
                  style={{ flex:1, padding:'6px 8px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:12, outline:'none' }}/>
                <input value={b.bis} onChange={e => { const u=[...(appData.sonderzeiten.betriebsruhe)]; u[i]={...u[i],bis:e.target.value}; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,betriebsruhe:u}})); }} placeholder="bis TT.MM.JJ"
                  style={{ flex:1, padding:'6px 8px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:12, outline:'none' }}/>
                <button onClick={() => { const u=appData.sonderzeiten.betriebsruhe.filter((_,j)=>j!==i); setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,betriebsruhe:u}})); }} style={{ width:24, height:24, borderRadius:6, border:'none', cursor:'pointer', background:'rgba(244,239,230,0.1)', color:'rgba(244,239,230,0.5)', fontSize:14 }}>×</button>
              </div>
            ))}
            <button onClick={() => { const u=[...(appData.sonderzeiten?.betriebsruhe||[]), {von:'',bis:''}]; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,betriebsruhe:u}})); }} style={{ width:'100%', padding:'5px 0', background:'transparent', border:'1px dashed rgba(244,239,230,0.2)', borderRadius:6, cursor:'pointer', color:'rgba(244,239,230,0.5)', fontFamily:'Manrope', fontSize:11 }}>+ Betriebsruhe hinzufügen</button>
          </div>

          {/* Feiertage */}
          <div style={{ background:'rgba(244,239,230,0.06)', borderRadius:10, padding:12, border:'1px solid rgba(244,239,230,0.1)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity:0.6, marginBottom:10 }}>Feiertage</div>
            {(appData.sonderzeiten?.feiertage || []).map((f, i) => (
              <div key={i} style={{ display:'flex', gap:4, marginBottom:6, alignItems:'center', flexWrap:'wrap' }}>
                <input value={f.datum} onChange={e => { const u=[...(appData.sonderzeiten.feiertage)]; u[i]={...u[i],datum:e.target.value}; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,feiertage:u}})); }} placeholder="Datum"
                  style={{ width:90, padding:'5px 7px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:11, outline:'none' }}/>
                <input value={f.name} onChange={e => { const u=[...(appData.sonderzeiten.feiertage)]; u[i]={...u[i],name:e.target.value}; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,feiertage:u}})); }} placeholder="Bezeichnung"
                  style={{ flex:1, minWidth:80, padding:'5px 7px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:11, outline:'none' }}/>
                <input value={f.zeit} onChange={e => { const u=[...(appData.sonderzeiten.feiertage)]; u[i]={...u[i],zeit:e.target.value}; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,feiertage:u}})); }} placeholder="Zeit"
                  style={{ width:80, padding:'5px 7px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:11, outline:'none' }}/>
                <button onClick={() => { const u=appData.sonderzeiten.feiertage.filter((_,j)=>j!==i); setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,feiertage:u}})); }} style={{ width:24, height:24, borderRadius:6, border:'none', cursor:'pointer', background:'rgba(244,239,230,0.1)', color:'rgba(244,239,230,0.5)', fontSize:14 }}>×</button>
              </div>
            ))}
            <button onClick={() => { const u=[...(appData.sonderzeiten?.feiertage||[]), {datum:'',name:'',zeit:''}]; setAppData(d=>({...d,sonderzeiten:{...d.sonderzeiten,feiertage:u}})); }} style={{ width:'100%', padding:'5px 0', background:'transparent', border:'1px dashed rgba(244,239,230,0.2)', borderRadius:6, cursor:'pointer', color:'rgba(244,239,230,0.5)', fontFamily:'Manrope', fontSize:11 }}>+ Feiertag hinzufügen</button>
          </div>
        </div>
      )}

      {section === 'hours' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
          {appData.hours.map((h, ri) => (
            <div key={ri} style={{
              background: 'rgba(244,239,230,0.06)', borderRadius: 10, padding: 12,
              border: '1px solid rgba(244,239,230,0.1)',
            }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 8 }}>
                <span style={{ fontFamily:'"DM Serif Display", serif', fontSize: 15, color: h.closed ? 'rgba(244,239,230,0.45)' : '#f4efe6' }}>{h.day}</span>
                <button onClick={() => toggleClosed(ri)} style={{
                  padding: '3px 8px', borderRadius: 6, cursor:'pointer', border: 'none',
                  background: h.closed ? '#c97d2630' : 'rgba(244,239,230,0.12)',
                  color: h.closed ? '#c97d26' : 'rgba(244,239,230,0.6)',
                  fontFamily:'JetBrains Mono, monospace', fontSize: 9.5, letterSpacing:'0.1em',
                }}>{h.closed ? 'RUHETAG' : 'Offen'}</button>
              </div>
              {!h.closed && (
                <div style={{ display:'flex', flexDirection:'column', gap: 6 }}>
                  {h.times.map((t, ti) => (
                    <div key={ti} style={{ display:'flex', gap: 6, alignItems:'center' }}>
                      <input
                        value={t}
                        onChange={e => updateHourTime(ri, ti, e.target.value)}
                        placeholder="00:00 – 00:00"
                        style={{
                          flex: 1, padding: '7px 10px', background: 'rgba(244,239,230,0.08)',
                          border: '1px solid rgba(244,239,230,0.15)', borderRadius: 7,
                          color: '#f4efe6', fontFamily:'"DM Serif Display", serif', fontSize: 13,
                          outline: 'none',
                        }}
                      />
                      {h.times.length > 1 && (
                        <button onClick={() => removeTimeSlot(ri, ti)} style={{
                          width: 26, height: 26, borderRadius: 6, border:'none', cursor:'pointer',
                          background: 'rgba(244,239,230,0.1)', color: 'rgba(244,239,230,0.5)',
                          fontFamily:'Manrope', fontSize: 14, display:'flex', alignItems:'center', justifyContent:'center',
                        }}>×</button>
                      )}
                    </div>
                  ))}
                  {h.times.length < 3 && (
                    <button onClick={() => addTimeSlot(ri)} style={{
                      padding: '5px 0', background: 'transparent', border: '1px dashed rgba(244,239,230,0.2)',
                      borderRadius: 7, cursor:'pointer', color: 'rgba(244,239,230,0.5)',
                      fontFamily:'Manrope', fontSize: 11,
                    }}>+ Zeitraum hinzufügen</button>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {section === 'contact' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          {[
            ['address', 'Adresse'],
            ['phone',   'Telefon'],
            ['email',   'E-Mail'],
            ['whatsapp','WhatsApp-Link (wa.me/…)'],
            ['ebike',   'E-Bike Laden'],
            ['wall',    'Auto laden'],
          ].map(([key, label]) => (
            <div key={key}>
              <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity: 0.55, marginBottom: 5 }}>{label}</div>
              <input
                value={appData.contact[key] || ''}
                onChange={e => updateContact(key, e.target.value)}
                style={{
                  width: '100%', padding: '9px 12px', background: 'rgba(244,239,230,0.08)',
                  border: '1px solid rgba(244,239,230,0.15)', borderRadius: 8,
                  color: '#f4efe6', fontFamily:'Manrope', fontSize: 13, outline:'none',
                  boxSizing: 'border-box',
                }}
              />
            </div>
          ))}
        </div>
      )}

      {section === 'texts' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          {[
            ['name',    'Brauerei-Name (oben im Header)'],
            ['tagline', 'Tagline (Startseite, 2 Zeilen mit \\n)'],
          ].map(([key, label]) => (
            <div key={key}>
              <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity: 0.55, marginBottom: 5 }}>{label}</div>
              {key === 'tagline' ? (
                <textarea
                  value={(appData.home && appData.home[key]) || ''}
                  onChange={e => setAppData(d => ({ ...d, home: { ...d.home, [key]: e.target.value } }))}
                  rows={3}
                  style={{
                    width: '100%', padding: '9px 12px', background: 'rgba(244,239,230,0.08)',
                    border: '1px solid rgba(244,239,230,0.15)', borderRadius: 8,
                    color: '#f4efe6', fontFamily:'Manrope', fontSize: 13, outline:'none',
                    boxSizing: 'border-box', resize: 'vertical',
                  }}
                />
              ) : (
                <input
                  value={(appData.home && appData.home[key]) || ''}
                  onChange={e => setAppData(d => ({ ...d, home: { ...d.home, [key]: e.target.value } }))}
                  style={{
                    width: '100%', padding: '9px 12px', background: 'rgba(244,239,230,0.08)',
                    border: '1px solid rgba(244,239,230,0.15)', borderRadius: 8,
                    color: '#f4efe6', fontFamily:'Manrope', fontSize: 13, outline:'none',
                    boxSizing: 'border-box',
                  }}
                />
              )}
            </div>
          ))}
        </div>
      )}

      {section === 'woche' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          <div>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity: 0.55, marginBottom: 5 }}>Kalenderwoche</div>
            <input value={appData.wochenkarte?.kw || ''} onChange={e => setAppData(d => ({ ...d, wochenkarte: { ...d.wochenkarte, kw: e.target.value } }))}
              placeholder="z.B. 21"
              style={{ width:'100%', padding:'9px 12px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:8, color:'#f4efe6', fontFamily:'Manrope', fontSize:13, outline:'none', boxSizing:'border-box' }}/>
          </div>

          {/* Bild-Upload */}
          <div>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity: 0.55, marginBottom: 8 }}>Wochenkarte Bild</div>
            {appData.wochenkarte?.bild ? (
              <div style={{ position:'relative' }}>
                <img src={appData.wochenkarte.bild} alt="Wochenkarte" style={{ width:'100%', borderRadius:8, display:'block', maxHeight:200, objectFit:'cover' }}/>
                <button onClick={() => setAppData(d => ({...d, wochenkarte:{...d.wochenkarte, bild:''}}))} style={{
                  position:'absolute', top:6, right:6, width:24, height:24, borderRadius:12, border:'none', cursor:'pointer',
                  background:'rgba(0,0,0,0.6)', color:'#fff', fontSize:14, display:'flex', alignItems:'center', justifyContent:'center',
                }}>×</button>
              </div>
            ) : (
              <label style={{
                display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
                padding:'20px', borderRadius:10, border:'1px dashed rgba(244,239,230,0.3)',
                cursor:'pointer', background:'rgba(244,239,230,0.04)',
              }}>
                <span style={{ fontSize:24, marginBottom:6 }}>📷</span>
                <span style={{ fontSize:12, color:'rgba(244,239,230,0.6)', fontFamily:'Manrope', textAlign:'center' }}>Foto der Wochenkarte tippen zum Hochladen</span>
                <input type="file" accept="image/*" style={{ display:'none' }} onChange={e => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  const reader = new FileReader();
                  reader.onload = ev => setAppData(d => ({...d, wochenkarte:{...d.wochenkarte, bild: ev.target.result}}));
                  reader.readAsDataURL(file);
                }}/>
              </label>
            )}
            <div style={{ fontSize:10.5, opacity:0.5, marginTop:6, lineHeight:1.4, fontFamily:'Manrope' }}>
              Foto mit dem Handy vom Ausdruck machen → hochladen → sofort in der App sichtbar.
            </div>
          </div>
          <div style={{ background:'rgba(201,125,38,0.08)', borderRadius:10, padding:12, border:'1px dashed rgba(201,125,38,0.3)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'#c97d26', marginBottom:8 }}>Sonderbier (Heim-Seite)</div>
            {[['name','Name (leer = nicht anzeigen)'],['desc','Beschreibung'],['price','Preis (ohne €)']].map(([key, lbl]) => (
              <div key={key} style={{ marginBottom:8 }}>
                <div style={{ fontSize:9.5, opacity:0.55, fontFamily:'JetBrains Mono, monospace', textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:4 }}>{lbl}</div>
                <input value={appData.sonderbier?.[key] || ''} onChange={e => setAppData(d => ({ ...d, sonderbier: { ...d.sonderbier, [key]: e.target.value } }))}
                  style={{ width:'100%', padding:'6px 10px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:12, outline:'none', boxSizing:'border-box' }}/>
              </div>
            ))}
          </div>
          {[['do','Donnerstag'],['fr','Freitag'],['sa','Samstag'],['so','Sonntag']].map(([dk, dlabel]) => {
            const dishes = appData.wochenkarte?.[dk] || [];
            const setDishes = (upd) => setAppData(d => ({ ...d, wochenkarte: { ...d.wochenkarte, [dk]: upd } }));
            return (
              <div key={dk} style={{ background:'rgba(244,239,230,0.06)', borderRadius:10, padding:12, border:'1px solid rgba(244,239,230,0.1)' }}>
                <div style={{ fontFamily:'"DM Serif Display", serif', fontSize:14, marginBottom:8, color:'#f4efe6' }}>{dlabel}</div>
                {dishes.map((item, idx) => (
                  <div key={idx} style={{ display:'flex', flexDirection:'column', gap:5, marginBottom:8, padding:'8px', background:'rgba(244,239,230,0.04)', borderRadius:8, border:'1px solid rgba(244,239,230,0.1)' }}>
                    <div style={{ display:'flex', gap:5, alignItems:'center' }}>
                      <input value={item.name} onChange={e => { const u=[...dishes]; u[idx]={...u[idx],name:e.target.value}; setDishes(u); }} placeholder="Gericht"
                        style={{ flex:2, padding:'6px 8px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:12, outline:'none' }}/>
                      <input value={item.price} onChange={e => { const u=[...dishes]; u[idx]={...u[idx],price:e.target.value}; setDishes(u); }} placeholder="€"
                        style={{ width:52, padding:'6px 8px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:12, outline:'none', textAlign:'center' }}/>
                      <button onClick={() => setDishes(dishes.filter((_,i)=>i!==idx))} style={{ width:24, height:24, borderRadius:6, border:'none', cursor:'pointer', background:'rgba(244,239,230,0.1)', color:'rgba(244,239,230,0.5)', fontSize:14 }}>×</button>
                    </div>
                    <input value={item.desc||''} onChange={e => { const u=[...dishes]; u[idx]={...u[idx],desc:e.target.value}; setDishes(u); }} placeholder="Beschreibung"
                      style={{ width:'100%', padding:'5px 8px', background:'rgba(244,239,230,0.06)', border:'1px solid rgba(244,239,230,0.12)', borderRadius:6, color:'rgba(244,239,230,0.8)', fontFamily:'Manrope', fontSize:11, outline:'none', boxSizing:'border-box' }}/>
                    <input value={item.beilage||''} onChange={e => { const u=[...dishes]; u[idx]={...u[idx],beilage:e.target.value}; setDishes(u); }} placeholder="Beilagen (optional)"
                      style={{ width:'100%', padding:'5px 8px', background:'rgba(244,239,230,0.06)', border:'1px solid rgba(244,239,230,0.12)', borderRadius:6, color:'rgba(244,239,230,0.7)', fontFamily:'Manrope', fontSize:11, outline:'none', boxSizing:'border-box' }}/>
                  </div>
                ))}
                <button onClick={() => setDishes([...dishes, { name:'', price:'', desc:'' }])} style={{ width:'100%', padding:'5px 0', background:'transparent', border:'1px dashed rgba(244,239,230,0.2)', borderRadius:6, cursor:'pointer', color:'rgba(244,239,230,0.5)', fontFamily:'Manrope', fontSize:11, marginTop:2 }}>+ Gericht hinzufügen</button>
              </div>
            );
          })}
        </div>
      )}

      {section === 'ampel' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          <p style={{ fontSize: 12, lineHeight: 1.5, opacity: 0.65, margin: 0 }}>
            Status wird automatisch aus dem Google-Sheet geladen. Hier kannst du einzelne Schichten manuell überschreiben — z.B. wenn das Sheet noch nicht aktuell ist.
          </p>
          {(appData.platzampel?.schichten || []).map((s, i) => (
            <div key={i} style={{ background:'rgba(244,239,230,0.06)', borderRadius:10, padding:'10px 12px', border:'1px solid rgba(244,239,230,0.1)', display:'flex', alignItems:'center', gap: 10 }}>
              <input
                value={s.label}
                onChange={e => {
                  const upd = appData.platzampel.schichten.map((x,j) => j===i ? {...x,label:e.target.value} : x);
                  setAppData(d => ({...d, platzampel:{...d.platzampel, schichten:upd}}));
                }}
                style={{ flex:1, padding:'6px 8px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:6, color:'#f4efe6', fontFamily:'Manrope', fontSize:12, outline:'none' }}
              />
              <div style={{ display:'flex', gap:4 }}>
                {[['grün','#16a34a'],['gelb','#ca8a04'],['rot','#dc2626']].map(([val, col]) => (
                  <button key={val} onClick={() => {
                    const upd = appData.platzampel.schichten.map((x,j) => j===i ? {...x,status:val} : x);
                    setAppData(d => ({...d, platzampel:{...d.platzampel, schichten:upd}}));
                  }} style={{
                    width:28, height:28, borderRadius:'50%', border: s.status===val ? '2px solid #fff' : '2px solid transparent',
                    background:col, cursor:'pointer', flexShrink:0,
                    boxShadow: s.status===val ? '0 0 0 2px '+col : 'none',
                  }}/>
                ))}
                <button onClick={() => {
                  const upd = appData.platzampel.schichten.filter((_,j)=>j!==i);
                  setAppData(d => ({...d, platzampel:{...d.platzampel, schichten:upd}}));
                }} style={{ width:28, height:28, borderRadius:6, border:'none', cursor:'pointer', background:'rgba(244,239,230,0.1)', color:'rgba(244,239,230,0.5)', fontSize:14 }}>×</button>
              </div>
            </div>
          ))}
          <button onClick={() => {
            const upd = [...(appData.platzampel?.schichten||[]), { label:'Neue Schicht', status:'grün' }];
            setAppData(d => ({...d, platzampel:{...d.platzampel, schichten:upd}}));
          }} style={{ padding:'8px 0', background:'transparent', border:'1px dashed rgba(244,239,230,0.2)', borderRadius:8, cursor:'pointer', color:'rgba(244,239,230,0.5)', fontFamily:'Manrope', fontSize:11 }}>
            + Schicht hinzufügen
          </button>
        </div>
      )}

      {section === 'aktuell' && (
        <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
          {/* Daily stamp add code */}
          <div style={{ background:'rgba(201,125,38,0.12)', borderRadius:10, padding:12, border:'1px solid rgba(201,125,38,0.3)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'#c97d26', marginBottom:6 }}>Stempel-Code (täglich)</div>
            <div style={{ fontFamily:'"DM Serif Display", serif', fontSize:36, color:'#c97d26', textAlign:'center', letterSpacing:10 }}>{typeof getDailyStampCode === 'function' ? getDailyStampCode() : '—'}</div>
            <div style={{ fontSize:10.5, opacity:0.6, textAlign:'center', marginTop:4, fontFamily:'Manrope' }}>Gast gibt diesen Code ein → +1 Stempel</div>
          </div>
          {/* Redemption codes */}
          <div style={{ background:'rgba(61,82,64,0.15)', borderRadius:10, padding:12, border:'1px solid rgba(61,82,64,0.3)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'rgba(244,239,230,0.6)', marginBottom:10 }}>Einlöse-Codes (täglich)</div>
            {[[5,'Hausbier'],[10,'Cocktail'],[20,'Essen frei']].map(([n, label]) => (
              <div key={n} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'6px 0', borderBottom:'1px dashed rgba(244,239,230,0.1)' }}>
                <span style={{ fontSize:12, color:'rgba(244,239,230,0.7)', fontFamily:'Manrope' }}>{n} Stempel → {label}</span>
                <span style={{ fontFamily:'"DM Serif Display", serif', fontSize:20, color:'#f4efe6', letterSpacing:4 }}>{typeof getRedemptionCode === 'function' ? getRedemptionCode(n) : '—'}</span>
              </div>
            ))}
            <div style={{ fontSize:10, opacity:0.5, marginTop:8, lineHeight:1.4, fontFamily:'Manrope' }}>Gast gibt Code ein → Stempel werden abgezogen</div>
          </div>
          {/* Review code */}
          <div style={{ background:'rgba(66,133,244,0.12)', borderRadius:10, padding:12, border:'1px solid rgba(66,133,244,0.3)' }}>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', color:'#4285F4', marginBottom:6 }}>⭐ Bewertungs-Code (täglich)</div>
            <div style={{ fontFamily:'"DM Serif Display", serif', fontSize:36, color:'#4285F4', textAlign:'center', letterSpacing:10 }}>{typeof getReviewCode === 'function' ? getReviewCode() : '—'}</div>
            <div style={{ fontSize:10.5, opacity:0.6, textAlign:'center', marginTop:4, fontFamily:'Manrope' }}>Gast zeigt Google-Bewertung → gibt diesen Code ein → +1 Stempel</div>
          </div>
          {[['text','Überschrift'],['sub','Untertext']].map(([key, label]) => (
            <div key={key}>
              <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9.5, letterSpacing:'0.16em', textTransform:'uppercase', opacity:0.55, marginBottom:5 }}>{label}</div>
              <input value={appData.news?.[key] || ''} onChange={e => setAppData(d => ({ ...d, news: { ...d.news, [key]: e.target.value } }))}
                style={{ width:'100%', padding:'9px 12px', background:'rgba(244,239,230,0.08)', border:'1px solid rgba(244,239,230,0.15)', borderRadius:8, color:'#f4efe6', fontFamily:'Manrope', fontSize:13, outline:'none', boxSizing:'border-box' }}/>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const btnDark = {
  width: 32, height: 32, borderRadius: 8, cursor:'pointer',
  background: 'rgba(244,239,230,0.08)', color: '#f4efe6', border:'1px solid rgba(244,239,230,0.15)',
  fontFamily:'Manrope', fontSize: 16, fontWeight: 700,
};

// ─────────────────────────────────────────────────────────────
// Tweaks panel
// ─────────────────────────────────────────────────────────────
const ZapfTweaks = ({ tweaks, setTweak }) => (
  <TweaksPanel>
    <TweakSection label="Stempelpass" />
    <TweakRadio  label="Stil" value={tweaks.stampStyle}
      options={[
        { value:'bierdeckel', label:'Bierdeckel' },
        { value:'klassisch',  label:'Karte' },
        { value:'krug',       label:'Krüge' },
      ]}
      onChange={(v)=>setTweak('stampStyle', v)} />
    <TweakSlider label="Stempel" value={tweaks.stampCount} min={0} max={20} step={1} unit=" / 20"
      onChange={(v)=>setTweak('stampCount', v)} />

    <TweakSection label="Inhalt" />
    <TweakSelect label="Saison" value={tweaks.showSeason}
      options={[
        { value:'fruehling', label:'Frühling — Bärlauchwochen' },
        { value:'sommer',    label:'Sommer — Biergarten' },
        { value:'herbst',    label:'Herbst — Schlachttag' },
        { value:'winter',    label:'Winter — Bockbier' },
      ]}
      onChange={(v)=>setTweak('showSeason', v)} />

    <TweakSection label="Theme" />
    <TweakColor label="Palette" value={tweaks.palette}
      options={[
        ['#3d5240','#c97d26','#f4efe6'],
        ['#2f4534','#d18a3a','#f6f1e7'],
        ['#475c40','#b8722a','#f1ebde'],
      ]}
      onChange={(v)=>{
        // Map back palette colors → key
        const key = Array.isArray(v) && v[0] === '#2f4534' ? 'moos'
                  : Array.isArray(v) && v[0] === '#475c40' ? 'abend'
                  : 'wald';
        setTweak('palette', key);
      }} />
  </TweaksPanel>
);

// Mount
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
