/* App shell — routing, persistence, Tweaks */
const { useState: useStateApp, useEffect: useEffectApp, useCallback: useCallbackApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "specialty": "Kinderchirurgie",
  "defaultFormat": "auto"
}/*EDITMODE-END*/;

function Toast({ msg }) {
  return <div className={`toast ${msg ? "show" : ""}`}>{msg}</div>;
}

function Topbar({ page, onHome, onList, specialty }) {
  return (
    <div className="topbar">
      <div className="brand">
        <span className="dot"/>
        Diktat
      </div>
      <div className="spec">{specialty}</div>
      <div className="nav">
        <button className={page === "home" ? "active" : ""} onClick={onHome}>Start</button>
        <button className={page === "list" ? "active" : ""} onClick={onList}>
          <Icon.List style={{width:14,height:14}}/> Aufnahmen
        </button>
      </div>
    </div>
  );
}

function App() {
  // Simple route state: "home" | "rec" | "list" | "detail"
  const [page, setPage] = useStateApp("home");
  const [currentId, setCurrentId] = useStateApp(null);
  const [recordings, setRecordings] = useStateApp(() => Store.load());
  const [toast, setToast] = useStateApp("");

  // Tweaks
  const tweaks = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];
  const [tweakState, setTweakState] = tweaks;

  const refresh = useCallbackApp(() => setRecordings(Store.load()), []);

  const showToast = useCallbackApp((msg) => {
    setToast(msg);
    setTimeout(() => setToast(""), 2000);
  }, []);

  // Kicks the user back to the home screen so the inline recorder is visible.
  const handleStartRecording = () => setPage("home");

  const handleDoneRecording = async ({ transcript, duration }) => {
    // Create recording skeleton
    const id = uid();
    const rec = {
      id,
      createdAt: Date.now(),
      updatedAt: Date.now(),
      duration,
      transcript,
      letter: "",
      title: "Neue Aufnahme",
      format: null,
      status: "processing",
      needsFormat: false,
    };
    Store.add(rec);
    refresh();
    setCurrentId(id);
    setPage("detail");

    // Detect format (unless user forced a specific one)
    let fmt = tweakState.defaultFormat && tweakState.defaultFormat !== "auto" ? tweakState.defaultFormat : null;
    if (!fmt) {
      const detected = await detectFormat(transcript);
      if (detected === "unsure") {
        Store.update(id, { needsFormat: true, status: "ready" });
        refresh();
        // Also generate title in background
        generateTitle(transcript).then(title => { Store.update(id, { title }); refresh(); });
        return;
      }
      fmt = detected;
    }

    // Generate letter + title in parallel
    try {
      const [letter, title] = await Promise.all([
        generateLetter(transcript, fmt, tweakState.specialty || "Kinderchirurgie"),
        generateTitle(transcript),
      ]);
      Store.update(id, { letter, title, format: fmt, status: "ready" });
      refresh();
    } catch (e) {
      Store.update(id, {
        letter: "Fehler bei der Briefgenerierung. Bitte im Ansicht-Modus Format wählen, um es erneut zu versuchen.",
        format: fmt,
        status: "ready",
        needsFormat: true,
      });
      refresh();
    }
  };

  const handleOpen = (id) => { setCurrentId(id); setPage("detail"); };
  const handleChange = (id, patch) => { Store.update(id, patch); refresh(); };
  const handleDelete = (id) => {
    Store.remove(id);
    refresh();
    setPage("list");
    showToast("Aufnahme gelöscht");
  };

  const currentRecording = recordings.find(r => r.id === currentId);

  return (
    <div className="app">
      <Topbar
        page={page}
        onHome={() => setPage("home")}
        onList={() => setPage("list")}
        specialty={tweakState.specialty || "Kinderchirurgie"}
      />

      {page === "home" && (
        <HomeScreen
          onDone={handleDoneRecording}
          onList={() => setPage("list")}
          recordingsCount={recordings.length}
        />
      )}
      {page === "list" && (
        <ListScreen
          recordings={recordings}
          onOpen={handleOpen}
          onNew={handleStartRecording}
        />
      )}
      {page === "detail" && currentRecording && (
        <DetailScreen
          recording={currentRecording}
          onBack={() => setPage("list")}
          onChange={handleChange}
          onDelete={handleDelete}
          showToast={showToast}
        />
      )}
      {page === "detail" && !currentRecording && (
        <div className="container-md" style={{padding:"60px 24px"}}>
          <button className="back" onClick={() => setPage("list")}>
            <Icon.ArrowLeft style={{width:14,height:14}}/> Zurück
          </button>
          <div style={{color:"var(--muted)", marginTop:20}}>Aufnahme nicht gefunden.</div>
        </div>
      )}

      <Toast msg={toast} />

      {/* Tweaks */}
      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Fachgebiet">
            <window.TweakSelect
              label="Spezialität"
              value={tweakState.specialty}
              onChange={(v) => setTweakState({ specialty: v })}
              options={[
                { value: "Kinderchirurgie", label: "Kinderchirurgie" },
                { value: "Allgemeinchirurgie", label: "Allgemeinchirurgie" },
                { value: "Pädiatrie", label: "Pädiatrie" },
                { value: "Viszeralchirurgie", label: "Viszeralchirurgie" },
                { value: "Unfallchirurgie", label: "Unfallchirurgie" },
                { value: "Urologie (Kinder)", label: "Kinderurologie" },
              ]}
            />
          </window.TweakSection>
          <window.TweakSection title="Brief-Format">
            <window.TweakRadio
              label="Standard-Format"
              value={tweakState.defaultFormat}
              onChange={(v) => setTweakState({ defaultFormat: v })}
              options={[
                { value: "auto", label: "Automatisch erkennen" },
                { value: "arztbrief", label: "Arztbrief" },
                { value: "konsult", label: "Konsultationsbericht" },
                { value: "soap", label: "SOAP-Notiz" },
                { value: "opbericht", label: "Operationsbericht" },
              ]}
            />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
