// App root + Tweaks -----------------------------------------------------

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "coldStartMemory": false,
  "density": "comfortable",
  "accountStatus": "subscribed",
  "trialPlan": "starter",
  "trialDay": 1
}/*EDITMODE-END*/;

function TweaksPanel({ visible, values, setValues }) {
  if (!visible) return null;
  return (
    <div className="fixed bottom-5 right-5 z-40 w-[320px] bg-white rounded-lg tweaks-panel fade-in overflow-hidden">
      <div className="px-4 py-3 border-b border-line flex items-center justify-between">
        <div className="text-[13px] font-semibold text-ink">Tweaks</div>
        <span className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">Prototyp</span>
      </div>
      <div className="p-4 space-y-4">
        <div>
          <div className="text-[12px] font-medium text-ink mb-2">Account-Status</div>
          <div className="grid grid-cols-2 gap-1 rounded-md border border-line overflow-hidden text-[12px]">
            <button onClick={() => setValues({ ...values, accountStatus: 'trial' })}
              className={`px-2 py-1.5 border-r border-line ${values.accountStatus === 'trial' ? 'bg-ink text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
              Testphase
            </button>
            <button onClick={() => setValues({ ...values, accountStatus: 'subscribed' })}
              className={`px-2 py-1.5 ${values.accountStatus === 'subscribed' ? 'bg-ink text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
              Abonniert
            </button>
          </div>
          {values.accountStatus === 'trial' ? (
            <>
              <div className="mt-2">
                <div className="text-[11px] text-ink-muted mb-1">Getestetes Abo</div>
                <div className="flex rounded-md border border-line overflow-hidden text-[11.5px]">
                  {['basic', 'starter', 'growth'].map(p => (
                    <button key={p} onClick={() => setValues({ ...values, trialPlan: p })}
                      className={`flex-1 px-2 py-1.5 border-r border-line last:border-r-0 capitalize ${values.trialPlan === p ? 'bg-[#3465E3] text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
                      {p}
                    </button>
                  ))}
                </div>
              </div>
              <div className="mt-2">
                <div className="text-[11px] text-ink-muted mb-1">Testtag (von 3)</div>
                <div className="flex rounded-md border border-line overflow-hidden text-[11.5px]">
                  {[1, 2, 3].map(d => (
                    <button key={d} onClick={() => setValues({ ...values, trialDay: d })}
                      className={`flex-1 px-2 py-1.5 border-r border-line last:border-r-0 tabular-nums ${values.trialDay === d ? 'bg-[#3465E3] text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
                      Tag {d}
                    </button>
                  ))}
                </div>
              </div>
            </>
          ) : (
            <div className="mt-2">
              <div className="text-[11px] text-ink-muted mb-1">Aktives Abo</div>
              <div className="flex rounded-md border border-line overflow-hidden text-[11.5px]">
                {['basic', 'starter', 'growth'].map(p => (
                  <button key={p} onClick={() => setValues({ ...values, trialPlan: p })}
                    className={`flex-1 px-2 py-1.5 border-r border-line last:border-r-0 capitalize ${values.trialPlan === p ? 'bg-[#3465E3] text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
                    {p}
                  </button>
                ))}
              </div>
            </div>
          )}
          {/* Onboarding gate replay */}
          <button
            onClick={() => {
              try { localStorage.removeItem('ls.onboardingDismissed'); } catch {}
              setValues({ ...values, accountStatus: 'trial', __onboardingReplay: Date.now() });
            }}
            className="w-full mt-2 px-2 py-1.5 rounded-md border border-dashed border-line text-[11.5px] text-ink-muted hover:bg-gray-50 hover:text-ink transition-colors">
            ↻ Onboarding-Gate erneut anzeigen
          </button>
        </div>
        <div>
          <div className="text-[12px] font-medium text-ink mb-2">Memory-Fläche</div>
          <div className="flex rounded-md border border-line overflow-hidden text-[12px]">
            <button onClick={() => setValues({ ...values, coldStartMemory: false })}
              className={`flex-1 px-2 py-1.5 ${!values.coldStartMemory ? 'bg-ink text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
              Gelernt
            </button>
            <button onClick={() => setValues({ ...values, coldStartMemory: true })}
              className={`flex-1 px-2 py-1.5 border-l border-line ${values.coldStartMemory ? 'bg-ink text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
              Cold-Start
            </button>
          </div>
          <div className="text-[11.5px] text-ink-muted mt-1.5 leading-snug">Wie sieht die Memory-Fläche aus, wenn ein neuer Nutzer noch nichts bewertet hat?</div>
        </div>
        <div>
          <div className="text-[12px] font-medium text-ink mb-2">Dichte der Lead-Liste</div>
          <div className="flex rounded-md border border-line overflow-hidden text-[12px]">
            <button onClick={() => setValues({ ...values, density: 'comfortable' })}
              className={`flex-1 px-2 py-1.5 ${values.density === 'comfortable' ? 'bg-ink text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
              Komfortabel
            </button>
            <button onClick={() => setValues({ ...values, density: 'compact' })}
              className={`flex-1 px-2 py-1.5 border-l border-line ${values.density === 'compact' ? 'bg-ink text-white' : 'text-ink-muted hover:bg-gray-50'}`}>
              Kompakt
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [profiles, setProfiles] = useState(PROFILES);
  const [profileId, setProfileId] = useState(PROFILES[0].id);
  const [tab, setTab] = useState('dashboard'); // dashboard · results · detail · memory
  const [openedLead, setOpenedLead] = useState(null);
  const [feedbackByProfile, setFeedbackByProfile] = useState({});
  const [memoryByProfile, setMemoryByProfile] = useState(() =>
    Object.fromEntries(PROFILES.map(p => [p.id, p.memory]))
  );
  const [wizardOpen, setWizardOpen] = useState(false);
  const [leadsFilter, setLeadsFilter] = useState(PROFILES[0].id); // defaults to active profile

  // Notifications
  const [notifDismissed, setNotifDismissed] = useState(new Set());
  const [notifRead, setNotifRead] = useState(new Set());
  const [patternWhy, setPatternWhy] = useState({}); // patternId → why text
  const notifItems = useMemo(
    () => buildNotifications(profiles, feedbackByProfile),
    [profiles, feedbackByProfile, memoryByProfile]
  );
  const dismissNotif = (id) => setNotifDismissed(s => new Set([...s, id]));
  const markNotifRead = (id) => setNotifRead(s => new Set([...s, id]));
  const actNotif = (item) => {
    if (item.profileId && item.profileId !== profileId) setProfileId(item.profileId);
    if (item.kind === 'review' || item.kind === 'edge') setTab('results');
    else if (item.kind === 'pattern') setTab('memory');
    markNotifRead(item.id);
  };
  const confirmPattern = (patternId, why) => {
    const m = memoryByProfile[profileId] || [];
    const next = m.map(x => x.id === patternId ? { ...x, confirmed: true } : x);
    setMemoryByProfile({ ...memoryByProfile, [profileId]: next });
    if (why) setPatternWhy({ ...patternWhy, [patternId]: why });
    toast.push(t('notif.pattern.confirmedLabel'), 'positive');
  };
  const rejectPattern = (patternId, why) => {
    const m = memoryByProfile[profileId] || [];
    const next = m.filter(x => x.id !== patternId);
    setMemoryByProfile({ ...memoryByProfile, [profileId]: next });
    if (why) setPatternWhy({ ...patternWhy, [patternId]: why });
    toast.push(t('notif.pattern.rejectedLabel'), 'default');
  };

  const [tweakValues, setTweakValues] = useState(TWEAK_DEFAULTS);
  const [tweaksVisible, setTweaksVisible] = useState(false);

  // Tweak-mode plumbing
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setTweaksVisible(true);
      if (d.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  useEffect(() => {
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: tweakValues }, '*');
  }, [tweakValues]);

  const profile = profiles.find(p => p.id === profileId) || profiles[0];
  const feedback = feedbackByProfile[profileId] || {};
  const setFeedback = (f) => setFeedbackByProfile({ ...feedbackByProfile, [profileId]: f });
  const memory = memoryByProfile[profileId] || [];
  const setMemory = (m) => setMemoryByProfile({ ...memoryByProfile, [profileId]: m });

  const toast = useToasts();

  // Pricing modal state
  const [pricingOpen, setPricingOpen] = useState(false);
  const [pricingInitialMode, setPricingInitialMode] = useState(null);

  // Onboarding gate (forced first-time pricing on fresh trial)
  const [onboardingOpen, setOnboardingOpen] = useState(() => {
    try {
      return tweakValues.accountStatus === 'trial'
        && !localStorage.getItem('ls.onboardingDismissed');
    } catch { return false; }
  });
  // Re-open automatically if user flips back to trial from tweaks and hasn't dismissed
  useEffect(() => {
    if (tweakValues.accountStatus !== 'trial') {
      setOnboardingOpen(false);
    }
  }, [tweakValues.accountStatus]);
  // Replay trigger from Tweaks panel
  useEffect(() => {
    if (tweakValues.__onboardingReplay && tweakValues.accountStatus === 'trial') {
      setOnboardingOpen(true);
    }
  }, [tweakValues.__onboardingReplay]);
  const closeOnboarding = () => {
    try { localStorage.setItem('ls.onboardingDismissed', '1'); } catch {}
    setOnboardingOpen(false);
  };

  const isTrial = tweakValues.accountStatus === 'trial';
  const currentPlan = SUBSCRIPTION_PLANS.find(p => p.id === tweakValues.trialPlan) || SUBSCRIPTION_PLANS[1];
  const trialCreditsUsed = Math.min(currentPlan.trialLeads, (tweakValues.trialDay - 1) * Math.ceil(currentPlan.trialLeads / 3) + 4);
  const trialCreditsLeft = Math.max(0, currentPlan.trialLeads - trialCreditsUsed);
  const trialDaysLeft = Math.max(0, 4 - tweakValues.trialDay);

  const openPricing = (mode) => { setPricingInitialMode(mode); setPricingOpen(true); };

  const handleSubscribe = (planId) => {
    setTweakValues({ ...tweakValues, accountStatus: 'subscribed', trialPlan: planId });
    setPricingOpen(false);
    toast.push(`Willkommen im ${SUBSCRIPTION_PLANS.find(p => p.id === planId).name}-Abo — Testphase läuft.`, 'positive');
  };
  const handleBuyPackage = (packId) => {
    const pack = ONEOFF_PACKAGES.find(p => p.id === packId);
    setPricingOpen(false);
    toast.push(`${pack.leads.toLocaleString('de-DE')} Leads aufgeladen.`, 'positive');
  };

  const switchProfile = (id) => {
    setProfileId(id);
    setLeadsFilter(id); // sync leads filter
    setOpenedLead(null);
    if (tab === 'detail') setTab('results');
    toast.push(`Profil gewechselt: ${profiles.find(p=>p.id===id).name}.`, 'default');
  };

  const createProfile = () => setWizardOpen(true);

  const onWizardCreate = (newProfile) => {
    setProfiles([...profiles, newProfile]);
    setMemoryByProfile({ ...memoryByProfile, [newProfile.id]: [] });
    setProfileId(newProfile.id);
    setTab('memory');
    setWizardOpen(false);
    toast.push(t('np.created'), 'positive');
  };

  return (
    <div className="min-h-screen bg-surface">
      {isTrial && (
        <TrialBanner
          daysLeft={trialDaysLeft}
          creditsLeft={trialCreditsLeft}
          creditsTotal={currentPlan.trialLeads}
          planName={currentPlan.name}
          onUpgrade={() => openPricing('sub')}
        />
      )}
      <NavHeader
        profile={profile}
        profiles={profiles}
        onSwitchProfile={switchProfile}
        onCreateProfile={createProfile}
        tab={tab}
        onTab={(id) => { setTab(id); setOpenedLead(null); }}
        notifItems={notifItems}
        notifDismissed={notifDismissed}
        notifRead={notifRead}
        onNotifAct={actNotif}
        onNotifDismiss={dismissNotif}
        onNotifMarkRead={markNotifRead}
        accountStatus={tweakValues.accountStatus}
        trialCreditsLeft={trialCreditsLeft}
        trialCreditsTotal={currentPlan.trialLeads}
        currentPlan={currentPlan}
        onOpenPricing={openPricing}
      />

      <main>
        {tab === 'dashboard' && (
          <ScreenDashboard
            onGoToLeads={() => setTab('results')}
            onStartLeads={() => setTab('results')}
            profiles={profiles}
            activeProfileId={profileId}
            setActiveProfileId={setProfileId}
            onCreateProfile={createProfile}
            notifItems={notifItems}
            notifDismissed={notifDismissed}
            onNotifAct={actNotif}
            onNotifDismiss={dismissNotif}
            feedbackByProfile={feedbackByProfile}
            onOpenProfileLeads={(p) => { setProfileId(p.id); setLeadsFilter(p.id); setTab('results'); }}
          />
        )}
        {tab === 'results' && (
          <LeadsTable
            profiles={profiles}
            feedbackByProfile={feedbackByProfile}
            setFeedbackByProfile={setFeedbackByProfile}
            activeFilter={leadsFilter}
            setActiveFilter={setLeadsFilter}
            onOpenLead={(lead, p) => { setProfileId(p.id); setOpenedLead(lead); setTab('detail'); }}
            density={tweakValues.density}
            toast={toast}
          />
        )}
        {tab === 'detail' && openedLead && (
          <ScreenDetail
            profile={profile}
            lead={openedLead}
            onBack={() => setTab('results')}
            feedback={feedback}
            setFeedback={setFeedback}
            toast={toast}
          />
        )}
        {tab === 'memory' && (
          <ScreenProfileDetail
            profile={profile}
            memory={memory}
            setMemory={setMemory}
            onGoToResults={() => setTab('results')}
            toast={toast}
            onConfirmPattern={confirmPattern}
            onRejectPattern={rejectPattern}
          />
        )}
        {tab === 'account' && (
          <ScreenAccount
            onBack={() => setTab('dashboard')}
            toast={toast}
            accountStatus={tweakValues.accountStatus}
            currentPlan={currentPlan}
            trialDaysLeft={trialDaysLeft}
            trialCreditsLeft={trialCreditsLeft}
            trialCreditsTotal={currentPlan.trialLeads}
            onOpenPricing={openPricing}
          />
        )}
      </main>

      <TweaksPanel visible={tweaksVisible} values={tweakValues} setValues={setTweakValues}/>
      <NewProfileWizard open={wizardOpen} onClose={() => setWizardOpen(false)} onCreate={onWizardCreate}/>
      <PricingModal
        open={pricingOpen}
        onClose={() => setPricingOpen(false)}
        accountStatus={tweakValues.accountStatus === 'trial' ? 'trial' : tweakValues.trialPlan}
        initialMode={pricingInitialMode}
        onSubscribe={handleSubscribe}
        onBuyPackage={handleBuyPackage}
      />
      <OnboardingGate
        open={onboardingOpen}
        onSubscribe={(planId) => {
          handleSubscribe(planId);
          closeOnboarding();
        }}
        onSkip={closeOnboarding}
      />
      <AIAssistant
        profiles={profiles}
        activeProfileId={profileId}
        feedbackByProfile={feedbackByProfile}
        onGoTo={({ tab: t, profileId: pid }) => {
          if (pid && pid !== profileId) setProfileId(pid);
          if (t) { setTab(t); setOpenedLead(null); }
        }}
      />
      {toast.node}
    </div>
  );
}

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