"use client";

import { useState, useCallback, useEffect, useEffectEvent } from "react";
import type { TrailDetailData } from "@/data/queries";
import { TrailOverview } from "./TrailOverview";
import { TrailWalk } from "./TrailWalk";
import { useJetstreamInvalidation } from "./jetstream";

type Props = {
  trail: TrailDetailData;
  cleanHandle: string;
  rkey: string;
  currentUserDid: string | null;
  initialEmbeds?: Array<[string, Promise<React.ReactElement>]>;
};

type ViewMode = "overview" | "walk";

export function TrailView({ trail, cleanHandle, rkey, currentUserDid, initialEmbeds }: Props) {
  const [viewMode, setViewMode] = useState<ViewMode>("overview");

  const onLeave = useEffectEvent(() => {
    setViewMode("overview");
  });

  useEffect(() => {
    return () => {
      onLeave();
    };
  }, []);

  // Check if current user can edit this trail
  const canEdit = currentUserDid === trail.header.creator.did;

  // Enable real-time presence updates via Jetstream
  // Active for both overview and walk modes
  const shouldRefresh = useCallback(
    (event: any) => {
      // Only care about commit events
      if (!event.commit) return false;

      // Only care about walk collection
      if (event.commit.collection !== "app.sidetrail.walk") return false;

      if (event.did === currentUserDid) {
        return false;
      }

      // For deletes, we can't check the record (it's deleted)
      // so refresh optimistically
      if (event.commit.operation === "delete") return true;

      // For creates/updates, check if this walk is for our trail
      return event.commit.record?.trail?.uri === trail.header.uri;
    },
    [trail.header.uri, currentUserDid],
  );

  useJetstreamInvalidation(shouldRefresh, true);

  if (viewMode === "overview") {
    return <TrailOverview trail={trail} onModeChange={setViewMode} canEdit={canEdit} />;
  }

  return (
    <TrailWalk
      trail={trail}
      cleanHandle={cleanHandle}
      rkey={rkey}
      onModeChange={setViewMode}
      initialEmbeds={initialEmbeds}
    />
  );
}
