/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakToggle */
const { useState, useEffect } = React;

// ============================================================
// Demo content — the messages a listener might encounter,
// and the replies a sharer receives back.
// ============================================================
const LISTENER_MESSAGES = {
  default: {
    seed: "rin",
    name: "Anonymous",
    time: "8 minutes ago",
    askLabel: "wants some advice",
    body: "My sister and I haven't talked in 6 months.\nNeither of us did anything wrong, exactly.\nIt just drifted. I don't know how to start."
  },
  career: {
    seed: "avery",
    name: "Anonymous",
    time: "21 minutes ago",
    askLabel: "just wants to be heard",
    body: "Took the pay cut for the job I thought I'd love.\nThree months in. Not what I imagined.\nI think I made a mistake and I'm scared to say it out loud."
  },
  late: {
    seed: "jules",
    name: "Anonymous",
    time: "2 minutes ago",
    askLabel: "just wants to be heard",
    body: "It's late. I have a presentation in the morning.\nI haven't been sleeping. I keep checking the time.\nI just want to know it's going to be okay."
  }
};

// Silent-only flow: no written replies are returned, so no reply payload is needed.


// ============================================================
// Tweakable defaults — copy variants
// ============================================================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "tone": "ceremonial",
  "messageScenario": "default",
  "showPathDots": false,
  "branchLayout": "two-col",
  "welcomeMark": "wordmark"
} /*EDITMODE-END*/;

// Copy presets keyed by tone
const COPY = {
  ceremonial: {
    welcomeTitle: "Welcome to Confide.",
    welcomeSub: "A safe room where strangers are received without being seen.\nNo names, no scores, no scroll.",
    branchTitle: "Are you here to speak,\nor to be present\nfor someone?",
    branchSub: "Choose softly. You can step between rooms anytime.",
    listenerPrelude: "Someone is about to trust you\nwith something true.",
    listenerAskTitle: "They asked: to be heard,\nor to be heard and hear back.",
    sharerNeedTitle: "What do you need right now?",
    sharerComposeTitle: "What's on your mind today?"
  },
  plain: {
    welcomeTitle: "Welcome to Confide",
    welcomeSub: "Anonymous support from real people, when you need it.",
    branchTitle: "Are you here to share, or to listen?",
    branchSub: "You can switch any time.",
    listenerPrelude: "Someone wants to share something with you.",
    listenerAskTitle: "They asked to be heard, with or without a reply.",
    sharerNeedTitle: "What would help right now?",
    sharerComposeTitle: "Take your time.\nWrite what's true."
  },
  warm: {
    welcomeTitle: "Hi. You found us.",
    welcomeSub: "Confide is a quiet place for the things you can't quite say out loud.\nWe'll keep it gentle.",
    branchTitle: "Are you here to speak,\nor to listen\nfor a stranger?",
    branchSub: "Both are precious. Pick whichever feels easier tonight.",
    listenerPrelude: "Someone is opening up to you.\nThank you for being here.",
    listenerAskTitle: "They want to be heard.\nWith or without words back.",
    sharerNeedTitle: "What do you need right now?",
    sharerComposeTitle: "Say it once.\nSomeone kind will be reading."
  }
};

// ============================================================
// App — owns route + history
// ============================================================
const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const copy = COPY[tweaks.tone] || COPY.ceremonial;
  const messageKeys = ["default", "career", "late"];
  const startIdx = Math.max(0, messageKeys.indexOf(tweaks.messageScenario));
  const [msgIdx, setMsgIdx] = useState(startIdx);
  const message = LISTENER_MESSAGES[messageKeys[msgIdx % messageKeys.length]];

  const [route, setRoute] = useState("welcome");
  const [history, setHistory] = useState([]);
  const [branch, setBranch] = useState(null); // 'listener' | 'sharer'
  const [sharerMode, setSharerMode] = useState(null); // 'words' | 'silent'
  const [sharerText, setSharerText] = useState("");
  const [listenerText, setListenerText] = useState("");
  // track how many messages the listener has interacted with (replied OR skipped) this session
  const [touched, setTouched] = useState(0);
  const exhausted = touched >= messageKeys.length;

  const go = (next, opts = {}) => {
    setHistory((h) => [...h, route]);
    setRoute(next);
    if (opts.branch !== undefined) setBranch(opts.branch);
    if (opts.sharerMode !== undefined) setSharerMode(opts.sharerMode);
  };
  const back = () => {
    setHistory((h) => {
      if (!h.length) return h;
      const prev = h[h.length - 1];
      setRoute(prev);
      return h.slice(0, -1);
    });
  };
  const reset = () => {
    setRoute("welcome");
    setHistory([]);
    setBranch(null);
    setTouched(0);
    setMsgIdx(startIdx);
    setSharerMode(null);
    setSharerText("");
    setListenerText("");
  };

  // ---- step indicator ----
  const stepInfo = (() => {
    // 5 dots representing the deepest path; both branches have ~5 steps to outcome
    if (route === "welcome") return { step: 1, total: 4 };
    if (branch === "listener") {
      if (route === "listener-ask") return { step: 2, total: 3 };
      if (route === "listener-passed" || route === "listener-sent") return { step: 3, total: 3 };
    }
    if (branch === "sharer") {
      if (route === "sharer-compose") return { step: 2, total: 3 };
      if (route === "sharer-listening") return { step: 3, total: 3 };
      if (route === "sharer-heard") return { step: 3, total: 3 };
    }
    return { step: 1, total: 4 };
  })();

  // background tone shifts subtly per branch
  const tone = branch === "sharer" ? "warm" : branch === "listener" ? "cool" : null;

  return (
    <>
      <div className="stage" key={route + ":" + msgIdx /* re-mount triggers reveal */}>
        <StageDecor tone={tone} />
        <BrandMark onClick={reset} />

        {route === "welcome" &&
        <WelcomeStep
          copy={copy}
          onChoose={(b) => {
            if (b === "listener") go("listener-ask", { branch: "listener" });else
            go("sharer-compose", { branch: "sharer", sharerMode: "silent" });
          }} />

        }

        {/* ---- LISTENER PATH ---- */}
        {route === "listener-ask" &&
        <ListenerAskMode
          copy={copy}
          message={message}
          onChoose={(c, text) => {
            const nextTouched = touched + 1;
            if (c === "stay") {
              setListenerText(text);
              setTouched(nextTouched);
              go("listener-sent");
            } else {
              if (nextTouched >= messageKeys.length) {
                setTouched(nextTouched);
                go("listener-caught-up");
              } else {
                setTouched(nextTouched);
                setMsgIdx((i) => (i + 1) % messageKeys.length);
              }
            }
          }} />

        }
        {route === "listener-passed" &&
        <ListenerPassed onContinue={() => {setHistory([]);setRoute("listener-ask");}} />
        }
        {route === "listener-caught-up" &&
        <ListenerCaughtUp
          touched={touched}
          onHome={reset}
          onNotify={() => reset()} />

        }
        {route === "listener-sent" &&
        <ListenerSent
          sentText={listenerText}
          message={message}
          onHome={reset}
          onDone={() => {
            if (exhausted) {
              setHistory([]);
              setRoute("listener-caught-up");
            } else {
              setHistory([]);
              setMsgIdx((i) => (i + 1) % messageKeys.length);
              setRoute("listener-ask");
            }
          }} />

        }

        {/* ---- SHARER PATH ---- */}
        {route === "sharer-compose" &&
        <SharerCompose
          mode={sharerMode}
          copy={copy}
          onSend={(t) => {setSharerText(t);go("sharer-listening");}} />

        }
        {route === "sharer-listening" &&
        <SharerListening mode={sharerMode} onArrived={() => setRoute("sharer-heard")} />
        }
        {route === "sharer-heard" &&
        <SharerHeard
          onDone={(where) => {
            if (where === "listener") {
              setBranch("listener");setHistory([]);setRoute("listener-ask");
            } else {
              reset();
            }
          }} />

        }

        {/* back link */}
        {history.length > 0 && route !== "sharer-listening" && route !== "sharer-heard" &&
        <button className="back-link" onClick={back}>
            <ArrowLeft size={12} /> step back
          </button>
        }
      </div>

      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection title="Voice">
          <TweakRadio
            label="Copy tone"
            value={tweaks.tone}
            onChange={(v) => setTweak("tone", v)}
            options={[
            { value: "ceremonial", label: "Ceremonial" },
            { value: "warm", label: "Warm" },
            { value: "plain", label: "Plain" }]
            } />
          
        </TweakSection>
        <TweakSection title="Listener message">
          <TweakSelect
            label="Scenario"
            value={tweaks.messageScenario}
            onChange={(v) => setTweak("messageScenario", v)}
            options={[
            { value: "default", label: "Drifted from sister (default)" },
            { value: "career", label: "Career regret, just be heard" },
            { value: "late", label: "Anxious, late at night" }]
            } />
          
        </TweakSection>
      </TweaksPanel>
    </>);

};

ReactDOM.createRoot(document.getElementById("app")).render(<App />);