const initialState = Object.freeze({
  mode: "chats",
  account: { id: "demo-account", label: "Demo account", synthetic: true },
  workspace: { id: "demo-workspace", label: "Sample project", synthetic: true },
  threads: [
    { id: "demo-thread", title: "Review the sample change", preview: "A synthetic conversation for store review" },
    { id: "demo-thread-2", title: "Explain the project", preview: "No private chat history is used" }
  ],
  messages: [
    { id: "demo-user", role: "user", text: "Review the sample change in this project.", status: "complete" },
    { id: "demo-assistant", role: "assistant", text: "I reviewed the synthetic change. It adds a safe connection-state label and a focused test.", status: "complete" }
  ],
  approval: { id: "demo-approval", title: "Run the sample test?", command: "npm test -- sample", status: "pending" },
  files: [
    { path: "src/sample-connection.js", additions: 3, deletions: 1 },
    { path: "src/sample-connection.test.js", additions: 6, deletions: 0 }
  ],
  usage: { fiveHourRemaining: 82, weeklyRemaining: 64 },
  responsePending: false
});

export function createReviewDemoState() {
  return structuredClone(initialState);
}

export function reviewDemoReducer(state, action) {
  switch (action.type) {
    case "navigate":
      return { ...state, mode: action.mode };
    case "open-chat":
      return { ...state, mode: "chat" };
    case "send": {
      const message = String(action.message ?? "").trim();
      if (!message || state.responsePending) return state;
      const suffix = state.messages.length;
      return {
        ...state,
        mode: "chat",
        responsePending: true,
        messages: [
          ...state.messages,
          { id: `demo-user-${suffix}`, role: "user", text: message, status: "complete" },
          { id: `demo-assistant-${suffix}`, role: "assistant", text: "This is a synthetic response. The review demo cannot access files or run commands.", status: "streaming" }
        ]
      };
    }
    case "complete-response":
      return {
        ...state,
        responsePending: false,
        messages: state.messages.map((message) => message.status === "streaming" ? { ...message, status: "complete" } : message)
      };
    case "decide-approval":
      return { ...state, approval: { ...state.approval, status: action.decision } };
    case "reset":
      return createReviewDemoState();
    default:
      return state;
  }
}
