1→"use client";
     2→
     3→import { useState, useEffect, useCallback } from "react";
     4→import { useRouter } from "next/navigation";
     5→import Link from "next/link";
     6→import toast from "react-hot-toast";
     7→import { createClient } from "@/lib/supabase/client";
     8→import { Button } from "@/components/ui/button";
     9→import { Input } from "@/components/ui/input";
    10→import { Label } from "@/components/ui/label";
    11→import { Card, CardContent } from "@/components/ui/card";
    12→import VoiceRecorder from "@/components/VoiceRecorder";
    13→import { csrfFetch, addCSRFTokenToFormData, initializeCSRF } from "@/lib/csrf-client";
    14→import {
    15→  HardHat,
    16→  ArrowLeft,
    17→  ArrowRight,
    18→  Loader2,
    19→  CheckCircle2,
    20→  Sparkles,
    21→  MapPin,
    22→  Clock,
    23→  Shield,
    24→  Edit3,
    25→  Wrench,
    26→  Calendar,
    27→  Zap,
    28→  Mic,
    29→} from "lucide-react";
    30→
    31→type Step = "trade" | "experience" | "location" | "availability" | "generating" | "review";
    32→
    33→const TRADES = [
    34→  "Labourer",
    35→  "Steel Fixer",
    36→  "Formworker",
    37→  "Carpenter",
    38→  "Electrician",
    39→  "Plumber",
    40→  "Concreter",
    41→  "Bricklayer",
    42→  "Painter",
    43→  "Roofer",
    44→  "Scaffolder",
    45→  "Tiler",
    46→  "Plasterer",
    47→  "Welder",
    48→  "Crane Operator",
    49→  "Excavator Operator",
    50→];
    51→
    52→const EXPERIENCE_OPTIONS = [
    53→  { label: "Less than 1 year", value: 0 },
    54→  { label: "1-3 years", value: 2 },
    55→  { label: "3-5 years", value: 4 },
    56→  { label: "5-10 years", value: 7 },
    57→  { label: "10+ years", value: 12 },
    58→];
    59→
    60→const AVAILABILITY_OPTIONS = [
    61→  { label: "Full-time", value: "full-time" as const, desc: "Mon-Fri, regular hours" },
    62→  { label: "Casual", value: "casual" as const, desc: "As needed, flexible" },
    63→  { label: "Weekends", value: "weekends" as const, desc: "Saturday & Sunday" },
    64→  { label: "Flexible", value: "flexible" as const, desc: "Any time, any days" },
    65→];
    66→
    67→interface ProfileData {
    68→  trade: string;
    69→  experience: number;
    70→  location: string;
    71→  availability: "full-time" | "casual" | "weekends" | "flexible";
    72→}
    73→
    74→interface GeneratedProfile {
    75→  bio: string;
    76→  skills: string[];
    77→  certifications: string[];
    78→}
    79→
    80→function closestExperience(years: number): number {
    81→  const values = EXPERIENCE_OPTIONS.map((o) => o.value);
    82→  return values.reduce((prev, curr) =>
    83→    Math.abs(curr - years) < Math.abs(prev - years) ? curr : prev
    84→  );
    85→}
    86→
    87→export default function ProfileBuildPage() {
    88→  const [step, setStep] = useState<Step>("trade");
    89→  const [loading, setLoading] = useState(true);
    90→  const [generating, setGenerating] = useState(false);
    91→  const [saving, setSaving] = useState(false);
    92→
    93→  // Form data
    94→  const [trade, setTrade] = useState<string>("");
    95→  const [experience, setExperience] = useState<number | null>(null);
    96→  const [location, setLocation] = useState("");
    97→  const [availability, setAvailability] = useState<ProfileData["availability"] | null>(null);
    98→
    99→  // Generated data
   100→  const [generatedBio, setGeneratedBio] = useState("");
   101→  const [generatedSkills, setGeneratedSkills] = useState<string[]>([]);
   102→  const [generatedCerts, setGeneratedCerts] = useState<string[]>([]);
   103→
   104→  // Editable states
   105→  const [editedBio, setEditedBio] = useState("");
   106→  const [editedSkills, setEditedSkills] = useState<string[]>([]);
   107→  const [editedCerts, setEditedCerts] = useState<string[]>([]);
   108→
   109→  // Voice flow
   110→  const [showVoice, setShowVoice] = useState(false);
   111→  const [voiceProcessing, setVoiceProcessing] = useState(false);
   112→  const [voiceStatus, setVoiceStatus] = useState("");
   113→  const [voiceError, setVoiceError] = useState<string | null>(null);
   114→
   115→  const router = useRouter();
   116→  const supabase = createClient();
   117→
   118→  useEffect(() => {
   119→    async function checkAuth() {
   120→      const {
   121→        data: { user },
   122→      } = await supabase.auth.getUser();
   123→      if (!user) {
   124→        router.push("/auth/login");
   125→        return;
   126→      }
   127→      // Initialize CSRF token for API calls
   128→      await initializeCSRF();
   129→      setLoading(false);
   130→    }
   131→    checkAuth();
   132→  }, [supabase.auth, router]);
   133→
   134→  async function generateProfile() {
   135→    if (!trade || experience === null || !location || !availability) return;
   136→
   137→    setGenerating(true);
   138→    setStep("generating");
   139→
   140→    try {
   141→      const response = await csrfFetch("/api/ai/generate-profile", {
   142→        method: "POST",
   143→        headers: { "Content-Type": "application/json" },
   144→        body: JSON.stringify({
   145→          trade,
   146→          experience,
   147→          location,
   148→          availability,
   149→        }),
   150→      });
   151→
   152→      if (!response.ok) {
   153→        const errorData = await response.json().catch(() => ({}));
   154→        if (response.status === 401) {
   155→          toast.error("Session expired. Please log in again.");
   156→          router.push("/auth/login");
   157→          return;
   158→        }
   159→        if (response.status === 429) {
   160→          toast.error("Too many requests. Please wait a few minutes and try again.");
   161→          setStep("availability");
   162→          return;
   163→        }
   164→        throw new Error(errorData.error || "Failed to generate profile");
   165→      }
   166→
   167→      const data: GeneratedProfile = await response.json();
   168→
   169→      setGeneratedBio(data.bio);
   170→      setGeneratedSkills(data.skills);
   171→      setGeneratedCerts(data.certifications);
   172→
   173→      // Initialize editable versions
   174→      setEditedBio(data.bio);
   175→      setEditedSkills(data.skills);
   176→      setEditedCerts(data.certifications);
   177→
   178→      setStep("review");
   179→    } catch (error) {
   180→      console.error("Generation error:", error);
   181→      const message = error instanceof Error ? error.message : "Failed to generate profile";
   182→      toast.error(`${message}. Please try again.`);
   183→      setStep("availability");
   184→    } finally {
   185→      setGenerating(false);
   186→    }
   187→  }
   188→
   189→  const handleVoiceComplete = useCallback(async (blob: Blob) => {
   190→    setVoiceProcessing(true);
   191→    setVoiceError(null);
   192→    setVoiceStatus("Transcribing your voice...");
   193→
   194→    try {
   195→      // Step 1: Transcribe (FormData with CSRF token)
   196→      const formData = new FormData();
   197→      formData.append("audio", blob, "recording.webm");
   198→      addCSRFTokenToFormData(formData);
   199→
   200→      const transcribeRes = await fetch("/api/ai/transcribe-voice", {
   201→        method: "POST",
   202→        body: formData,
   203→      });
   204→
   205→      if (!transcribeRes.ok) {
   206→        if (transcribeRes.status === 429) {
   207→          throw new Error("Too many requests. Please wait a few minutes.");
   208→        }
   209→        const errData = await transcribeRes.json().catch(() => ({}));
   210→        throw new Error(errData.error || "Failed to transcribe audio");
   211→      }
   212→
   213→      const { text } = await transcribeRes.json();
   214→      if (!text) throw new Error("No speech detected. Please try again.");
   215→
   216→      setVoiceStatus("Understanding your details...");
   217→
   218→      // Step 2: Parse profile fields (JSON with CSRF header)
   219→      const parseRes = await csrfFetch("/api/ai/parse-profile-voice", {
   220→        method: "POST",
   221→        headers: { "Content-Type": "application/json" },
   222→        body: JSON.stringify({ transcript: text }),
   223→      });
   224→
   225→      if (!parseRes.ok) {
   226→        const errData = await parseRes.json().catch(() => ({}));
   227→        throw new Error(errData.error || "Failed to parse your details");
   228→      }
   229→
   230→      const parsed = await parseRes.json();
   231→
   232→      // Pre-fill fields
   233→      if (parsed.trade) setTrade(parsed.trade);
   234→      if (parsed.experience_years !== null && parsed.experience_years !== undefined) {
   235→        setExperience(closestExperience(parsed.experience_years));
   236→      }
   237→      if (parsed.location) setLocation(parsed.location);
   238→      if (parsed.availability) setAvailability(parsed.availability);
   239→
   240→      // Check what we got and move to the right step
   241→      setShowVoice(false);
   242→      setVoiceStatus("");
   243→
   244→      const hasTrade = !!parsed.trade;
   245→      const hasExp = parsed.experience_years !== null && parsed.experience_years !== undefined;
   246→      const hasLoc = !!parsed.location;
   247→      const hasAvail = !!parsed.availability;
   248→
   249→      if (hasTrade && hasExp && hasLoc && hasAvail) {
   250→        // All fields filled — go straight to generating
   251→        // Need to call generateProfile after state updates, so use a timeout
   252→        setTimeout(() => {
   253→          setStep("generating");
   254→        }, 0);
   255→      } else if (!hasTrade) {
   256→        setStep("trade");
   257→      } else if (!hasExp) {
   258→        setStep("experience");
   259→      } else if (!hasLoc) {
   260→        setStep("location");
   261→      } else {
   262→        setStep("availability");
   263→      }
   264→    } catch (error) {
   265→      console.error("Voice processing error:", error);
   266→      setVoiceError(error instanceof Error ? error.message : "Something went wrong. Please try again.");
   267→      setVoiceStatus("");
   268→    } finally {
   269→      setVoiceProcessing(false);
   270→    }
   271→  }, []);
   272→
   273→  // When step changes to "generating" from voice flow, trigger profile generation
   274→  useEffect(() => {
   275→    if (step === "generating" && !generating && trade && experience !== null && location && availability) {
   276→      generateProfile();
   277→    }
   278→    // eslint-disable-next-line react-hooks/exhaustive-deps
   279→  }, [step]);
   280→
   281→  async function handleSave() {
   282→    setSaving(true);
   283→
   284→    try {
   285→      const {
   286→        data: { user },
   287→      } = await supabase.auth.getUser();
   288→      if (!user) throw new Error("Not authenticated");
   289→
   290→      // Update or create worker profile
   291→      const { data: existingProfile } = await supabase
   292→        .from("worker_profiles")
   293→        .select("id")
   294→        .eq("profile_id", user.id)
   295→        .single();
   296→
   297→      const profileData = {
   298→        profile_id: user.id,
   299→        trades: [trade],
   300→        experience_years: experience,
   301→        availability,
   302→        certifications: editedCerts,
   303→        bio: editedBio,
   304→        ai_extracted: {
   305→          skills: editedSkills,
   306→          generated_at: new Date().toISOString(),
   307→          original_bio: generatedBio,
   308→          original_skills: generatedSkills,
   309→          original_certs: generatedCerts,
   310→        },
   311→      };
   312→
   313→      if (existingProfile) {
   314→        await supabase
   315→          .from("worker_profiles")
   316→          .update(profileData)
   317→          .eq("profile_id", user.id);
   318→      } else {
   319→        await supabase.from("worker_profiles").insert(profileData);
   320→      }
   321→
   322→      // Update main profile
   323→      await supabase
   324→        .from("profiles")
   325→        .update({
   326→          suburb: location,
   327→          onboarding_completed: true,
   328→        })
   329→        .eq("id", user.id);
   330→
   331→      router.push("/dashboard");
   332→      router.refresh();
   333→    } catch (error) {
   334→      console.error("Save error:", error);
   335→      toast.error("Failed to save profile. Please try again.");
   336→    } finally {
   337→      setSaving(false);
   338→    }
   339→  }
   340→
   341→  const stepOrder: Step[] = ["trade", "experience", "location", "availability", "generating", "review"];
   342→  const currentIndex = stepOrder.indexOf(step);
   343→  const totalSteps = 4; // Only count user-facing steps
   344→
   345→  if (loading) {
   346→    return (
   347→

   348→        <Loader2 className="h-8 w-8 animate-spin text-primary" />
   349→

   350→    );
   351→  }
   352→
   353→  return (
   354→

   355→
   356→        {/* Progress bar */}
   357→        {step !== "generating" && step !== "review" && (
   358→

   359→            {Array.from({ length: totalSteps }, (_, i) => (
   360→              <div
   361→                key={i}
   362→                className={`h-1.5 flex-1 rounded-full transition-colors ${
   363→                  i <= currentIndex ? "bg-primary" : "bg-muted"
   364→                }`}
   365→              />
   366→            ))}
   367→

   368→        )}
   369→
   370→        {/* Step: Trade */}
   371→        {step === "trade" && (
   372→

   373→            <StepHeader
   374→              icon={<Wrench className="h-5 w-5" />}
   375→              title="What's your trade?"
   376→              subtitle="Pick your primary trade"
   377→            />
   378→
   379→            {/* Voice option */}
   380→            {!showVoice && (
   381→              <button
   382→                onClick={() => setShowVoice(true)}
   383→                className="mt-6 flex w-full items-center justify-center gap-3 rounded-xl border-2 border-dashed border-primary/40 bg-primary/5 px-5 py-4 text-base font-medium text-primary transition-colors hover:border-primary hover:bg-primary/10 active:scale-95"
   384→                style={{ minHeight: "64px" }}
   385→              >
   386→                <Mic className="h-6 w-6" />
   387→                Or tell us with your voice
   388→              </button>
   389→            )}
   390→
   391→            {showVoice && (
   392→              <Card className="mt-6">
   393→                <CardContent className="flex flex-col items-center gap-4 pt-6">
   394→

   395→                    Say something like: “I'm a chippie with 8 years experience in Parramatta, looking for full-time work”
   396→

   397→
   398→                  {voiceProcessing ? (
   399→

   400→                      <Loader2 className="h-10 w-10 animate-spin text-primary" />
   401→
{voiceStatus}

   402→

   403→                  ) : (
   404→                    <VoiceRecorder onRecordingComplete={handleVoiceComplete} />
   405→                  )}
   406→
   407→                  {voiceError && (
   408→
{voiceError}

   409→                  )}
   410→
   411→                  <button
   412→                    onClick={() => {
   413→                      setShowVoice(false);
   414→                      setVoiceError(null);
   415→                    }}
   416→                    className="text-sm text-muted-foreground hover:text-foreground"
   417→                  >
   418→                    Cancel — I'll tap instead
   419→                  </button>
   420→                </CardContent>
   421→              </Card>
   422→            )}
   423→
   424→

   425→              {TRADES.map((t) => (
   426→                <button
   427→                  key={t}
   428→                  onClick={() => {
   429→                    setTrade(t);
   430→                    setStep("experience");
   431→                  }}
   432→                  className={`rounded-xl border-2 px-4 py-4 text-left text-base font-medium transition-colors active:scale-95 ${
   433→                    trade === t
   434→                      ? "border-primary bg-primary/10 text-primary"
   435→                      : "border-border hover:border-primary/50"
   436→                  }`}
   437→                  style={{ minHeight: "64px" }}
   438→                >
   439→                  {t}
   440→                </button>
   441→              ))}
   442→

   443→

   444→        )}
   445→
   446→        {/* Step: Experience */}
   447→        {step === "experience" && (
   448→

   449→            <StepHeader
   450→              icon={<Clock className="h-5 w-5" />}
   451→              title="Your experience?"
   452→              subtitle="Years in construction"
   453→            />
   454→
   455→

   456→              {EXPERIENCE_OPTIONS.map((opt) => (
   457→                <button
   458→                  key={opt.value}
   459→                  onClick={() => {
   460→                    setExperience(opt.value);
   461→                    setStep("location");
   462→                  }}
   463→                  className={`flex w-full items-center justify-between rounded-xl border-2 px-5 text-left text-base font-medium transition-colors active:scale-95 ${
   464→                    experience === opt.value
   465→                      ? "border-primary bg-primary/10 text-primary"
   466→                      : "border-border hover:border-primary/50"
   467→                  }`}
   468→                  style={{ minHeight: "64px" }}
   469→                >
   470→                  {opt.label}
   471→                  <ArrowRight className="h-5 w-5 text-muted-foreground" />
   472→                </button>
   473→              ))}
   474→

   475→
   476→            <button
   477→              onClick={() => setStep("trade")}
   478→              className="mt-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
   479→            >
   480→              <ArrowLeft className="h-4 w-4" />
   481→              Back
   482→            </button>
   483→

   484→        )}
   485→
   486→        {/* Step: Location */}
   487→        {step === "location" && (
   488→

   489→            <StepHeader
   490→              icon={<MapPin className="h-5 w-5" />}
   491→              title="Where are you based?"
   492→              subtitle="Your suburb or area"
   493→            />
   494→
   495→            <form
   496→              onSubmit={(e) => {
   497→                e.preventDefault();
   498→                if (location.trim()) setStep("availability");
   499→              }}
   500→              className="mt-6 space-y-4"
   501→            >
   502→

   503→                Suburb or Area
   504→                <Input
   505→                  id="location"
   506→                  placeholder="e.g. Parramatta, Blacktown"
   507→                  value={location}
   508→                  onChange={(e) => setLocation(e.target.value)}
   509→                  required
   510→                  autoFocus
   511→                  className="h-14 text-base"
   512→                />
   513→

   514→

   515→                We'll match you to nearby jobs
   516→

   517→
   518→

   519→                <Button
   520→                  type="button"
   521→                  variant="outline"
   522→                  onClick={() => setStep("experience")}
   523→                  className="h-14 w-14 p-0"
   524→                >
   525→                  <ArrowLeft className="h-5 w-5" />
   526→                </Button>
   527→                <Button
   528→                  type="submit"
   529→                  disabled={!location.trim()}
   530→                  className="h-14 flex-1 gap-2 text-base font-semibold"
   531→                >
   532→                  Continue
   533→                  <ArrowRight className="h-5 w-5" />
   534→                </Button>
   535→

   536→            </form>
   537→

   538→        )}
   539→
   540→        {/* Step: Availability */}
   541→        {step === "availability" && (
   542→

   543→            <StepHeader
   544→              icon={<Calendar className="h-5 w-5" />}
   545→              title="Your availability?"
   546→              subtitle="When can you work?"
   547→            />
   548→
   549→

   550→              {AVAILABILITY_OPTIONS.map((opt) => (
   551→                <button
   552→                  key={opt.value}
   553→                  onClick={() => {
   554→                    setAvailability(opt.value);
   555→                    generateProfile();
   556→                  }}
   557→                  className={`flex w-full items-start justify-between rounded-xl border-2 px-5 py-4 text-left transition-colors active:scale-95 ${
   558→                    availability === opt.value
   559→                      ? "border-primary bg-primary/10"
   560→                      : "border-border hover:border-primary/50"
   561→                  }`}
   562→                  style={{ minHeight: "64px" }}
   563→                >
   564→

   565→                    <p className={`text-base font-semibold ${availability === opt.value ? "text-primary" : ""}`}>
   566→                      {opt.label}
   567→

   568→
{opt.desc}

   569→

   570→                  <Zap className="h-5 w-5 shrink-0 text-primary" />
   571→                </button>
   572→              ))}
   573→

   574→
   575→            <button
   576→              onClick={() => setStep("location")}
   577→              className="mt-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
   578→            >
   579→              <ArrowLeft className="h-4 w-4" />
   580→              Back
   581→            </button>
   582→

   583→        )}
   584→
   585→        {/* Step: Generating */}
   586→        {step === "generating" && (
   587→

   588→

   589→              <Sparkles className="h-10 w-10 animate-pulse text-primary" />
   590→

   591→
Building your profile...

   592→

   593→              AI is generating your bio, skills, and certifications
   594→

   595→

   596→

   597→

   598→

   599→

   600→

   601→        )}
   602→
   603→        {/* Step: Review */}
   604→        {step === "review" && (
   605→

   606→

   607→

   608→                <Sparkles className="h-5 w-5" />
   609→

   610→

   611→
Review & Edit

   612→

   613→                  AI generated this — customise as needed
   614→

   615→

   616→

   617→
   618→            {/* Your Answers Summary */}
   619→            <Card className="mt-6">
   620→              <CardContent className="space-y-3 pt-6">
   621→

   622→

   623→                    <Wrench className="h-4 w-4 text-muted-foreground" />
   624→                    {trade}
   625→

   626→                  <button
   627→                    onClick={() => setStep("trade")}
   628→                    className="text-xs text-primary hover:underline"
   629→                  >
   630→                    Change
   631→                  </button>
   632→

   633→

   634→

   635→                    <Clock className="h-4 w-4 text-muted-foreground" />
   636→
   637→                      {EXPERIENCE_OPTIONS.find((o) => o.value === experience)?.label}
   638→
   639→

   640→                  <button
   641→                    onClick={() => setStep("experience")}
   642→                    className="text-xs text-primary hover:underline"
   643→                  >
   644→                    Change
   645→                  </button>
   646→

   647→

   648→

   649→                    <MapPin className="h-4 w-4 text-muted-foreground" />
   650→                    {location}
   651→

   652→                  <button
   653→                    onClick={() => setStep("location")}
   654→                    className="text-xs text-primary hover:underline"
   655→                  >
   656→                    Change
   657→                  </button>
   658→

   659→              </CardContent>
   660→            </Card>
   661→
   662→            {/* Bio */}
   663→

   664→

   665→
   666→                  <Sparkles className="h-4 w-4 text-primary" />
   667→                  Your Bio
   668→
   669→                AI-generated
   670→

   671→              <textarea
   672→                value={editedBio}
   673→                onChange={(e) => setEditedBio(e.target.value)}
   674→                className="min-h-[120px] w-full rounded-xl border-2 border-border bg-background px-4 py-3 text-base focus:border-primary focus:outline-none"
   675→                placeholder="Your professional bio..."
   676→              />
   677→

   678→
   679→            {/* Skills */}
   680→

   681→

   682→
   683→                  <Zap className="h-4 w-4 text-primary" />
   684→                  Skills
   685→
   686→                Tap to remove
   687→

   688→

   689→                {editedSkills.map((skill, idx) => (
   690→                  <button
   691→                    key={idx}
   692→                    onClick={() => setEditedSkills(editedSkills.filter((_, i) => i !== idx))}
   693→                    className="rounded-full border-2 border-primary bg-primary/10 px-4 py-2 text-sm font-medium text-primary transition-colors hover:bg-primary/20 active:scale-95"
   694→                  >
   695→                    {skill} ×
   696→                  </button>
   697→                ))}
   698→

   699→

   700→
   701→            {/* Certifications */}
   702→

   703→

   704→
   705→                  <Shield className="h-4 w-4 text-primary" />
   706→                  Certifications
   707→
   708→                Tap to remove
   709→

   710→

   711→                {editedCerts.map((cert, idx) => (
   712→                  <button
   713→                    key={idx}
   714→                    onClick={() => setEditedCerts(editedCerts.filter((_, i) => i !== idx))}
   715→                    className="flex w-full items-center justify-between rounded-xl border-2 border-border bg-background px-4 py-3 text-left text-sm font-medium transition-colors hover:border-destructive hover:bg-destructive/5 active:scale-95"
   716→                  >
   717→                    {cert}
   718→                    Remove
   719→                  </button>
   720→                ))}
   721→

   722→

   723→

   724→        )}
   725→
   726→
   727→      {/* Bottom sticky CTA - only show on review step */}
   728→      {step === "review" && (
   729→

   730→

   731→            <Button
   732→              onClick={handleSave}
   733→              className="h-16 w-full gap-2 text-lg font-semibold"
   734→              disabled={saving}
   735→            >
   736→              {saving ? (
   737→                <>
   738→                  <Loader2 className="h-6 w-6 animate-spin" />
   739→                  Saving profile...
   740→                </>
   741→              ) : (
   742→                <>
   743→                  <CheckCircle2 className="h-6 w-6" />
   744→                  Save My Profile
   745→                </>
   746→              )}
   747→            </Button>
   748→

   749→

   750→      )}
   751→

   752→  );
   753→}
   754→
   755→function StepHeader({
   756→  icon,
   757→  title,
   758→  subtitle,
   759→}: {
   760→  icon: React.ReactNode;
   761→  title: string;
   762→  subtitle: string;
   763→}) {
   764→  return (
   765→

   766→

   767→        {icon}
   768→

   769→

   770→
{title}

   771→
{subtitle}

   772→

   773→

   774→  );
   775→}
   776→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import toast from "react-hot-toast";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import VoiceRecorder from "@/components/VoiceRecorder";
import { csrfFetch, addCSRFTokenToFormData, initializeCSRF } from "@/lib/csrf-client";
import {
  HardHat,
  ArrowLeft,
  ArrowRight,
  Loader2,
  CheckCircle2,
  Sparkles,
  MapPin,
  Clock,
  Shield,
  Edit3,
  Wrench,
  Calendar,
  Zap,
  Mic,
} from "lucide-react";

type Step = "trade" | "experience" | "location" | "availability" | "generating" | "review";

const TRADES = [
  "Labourer",
  "Steel Fixer",
  "Formworker",
  "Carpenter",
  "Electrician",
  "Plumber",
  "Concreter",
  "Bricklayer",
  "Painter",
  "Roofer",
  "Scaffolder",
  "Tiler",
  "Plasterer",
  "Welder",
  "Crane Operator",
  "Excavator Operator",
];

const EXPERIENCE_OPTIONS = [
  { label: "Less than 1 year", value: 0 },
  { label: "1-3 years", value: 2 },
  { label: "3-5 years", value: 4 },
  { label: "5-10 years", value: 7 },
  { label: "10+ years", value: 12 },
];

const AVAILABILITY_OPTIONS = [
  { label: "Full-time", value: "full-time" as const, desc: "Mon-Fri, regular hours" },
  { label: "Casual", value: "casual" as const, desc: "As needed, flexible" },
  { label: "Weekends", value: "weekends" as const, desc: "Saturday & Sunday" },
  { label: "Flexible", value: "flexible" as const, desc: "Any time, any days" },
];

interface ProfileData {
  trade: string;
  experience: number;
  location: string;
  availability: "full-time" | "casual" | "weekends" | "flexible";
}

interface GeneratedProfile {
  bio: string;
  skills: string[];
  certifications: string[];
}

function closestExperience(years: number): number {
  const values = EXPERIENCE_OPTIONS.map((o) => o.value);
  return values.reduce((prev, curr) =>
    Math.abs(curr - years) < Math.abs(prev - years) ? curr : prev
  );
}

export default function ProfileBuildPage() {
  const [step, setStep] = useState<Step>("trade");
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [saving, setSaving] = useState(false);

  // Form data
  const [trade, setTrade] = useState<string>("");
  const [experience, setExperience] = useState<number | null>(null);
  const [location, setLocation] = useState("");
  const [availability, setAvailability] = useState<ProfileData["availability"] | null>(null);

  // Generated data
  const [generatedBio, setGeneratedBio] = useState("");
  const [generatedSkills, setGeneratedSkills] = useState<string[]>([]);
  const [generatedCerts, setGeneratedCerts] = useState<string[]>([]);

  // Editable states
  const [editedBio, setEditedBio] = useState("");
  const [editedSkills, setEditedSkills] = useState<string[]>([]);
  const [editedCerts, setEditedCerts] = useState<string[]>([]);

  // Voice flow
  const [showVoice, setShowVoice] = useState(false);
  const [voiceProcessing, setVoiceProcessing] = useState(false);
  const [voiceStatus, setVoiceStatus] = useState("");
  const [voiceError, setVoiceError] = useState<string | null>(null);

  const router = useRouter();
  const supabase = createClient();

  useEffect(() => {
    async function checkAuth() {
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) {
        router.push("/auth/login");
        return;
      }
      // Initialize CSRF token for API calls
      await initializeCSRF();
      setLoading(false);
    }
    checkAuth();
  }, [supabase.auth, router]);

  async function generateProfile() {
    if (!trade || experience === null || !location || !availability) return;

    setGenerating(true);
    setStep("generating");

    try {
      const response = await csrfFetch("/api/ai/generate-profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          trade,
          experience,
          location,
          availability,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        if (response.status === 401) {
          toast.error("Session expired. Please log in again.");
          router.push("/auth/login");
          return;
        }
        if (response.status === 429) {
          toast.error("Too many requests. Please wait a few minutes and try again.");
          setStep("availability");
          return;
        }
        throw new Error(errorData.error || "Failed to generate profile");
      }

      const data: GeneratedProfile = await response.json();

      setGeneratedBio(data.bio);
      setGeneratedSkills(data.skills);
      setGeneratedCerts(data.certifications);

      // Initialize editable versions
      setEditedBio(data.bio);
      setEditedSkills(data.skills);
      setEditedCerts(data.certifications);

      setStep("review");
    } catch (error) {
      console.error("Generation error:", error);
      const message = error instanceof Error ? error.message : "Failed to generate profile";
      toast.error(`${message}. Please try again.`);
      setStep("availability");
    } finally {
      setGenerating(false);
    }
  }

  const handleVoiceComplete = useCallback(async (blob: Blob) => {
    setVoiceProcessing(true);
    setVoiceError(null);
    setVoiceStatus("Transcribing your voice...");

    try {
      // Step 1: Transcribe (FormData with CSRF token)
      const formData = new FormData();
      formData.append("audio", blob, "recording.webm");
      addCSRFTokenToFormData(formData);

      const transcribeRes = await fetch("/api/ai/transcribe-voice", {
        method: "POST",
        body: formData,
      });

      if (!transcribeRes.ok) {
        if (transcribeRes.status === 429) {
          throw new Error("Too many requests. Please wait a few minutes.");
        }
        const errData = await transcribeRes.json().catch(() => ({}));
        throw new Error(errData.error || "Failed to transcribe audio");
      }

      const { text } = await transcribeRes.json();
      if (!text) throw new Error("No speech detected. Please try again.");

      setVoiceStatus("Understanding your details...");

      // Step 2: Parse profile fields (JSON with CSRF header)
      const parseRes = await csrfFetch("/api/ai/parse-profile-voice", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ transcript: text }),
      });

      if (!parseRes.ok) {
        const errData = await parseRes.json().catch(() => ({}));
        throw new Error(errData.error || "Failed to parse your details");
      }

      const parsed = await parseRes.json();

      // Pre-fill fields
      if (parsed.trade) setTrade(parsed.trade);
      if (parsed.experience_years !== null && parsed.experience_years !== undefined) {
        setExperience(closestExperience(parsed.experience_years));
      }
      if (parsed.location) setLocation(parsed.location);
      if (parsed.availability) setAvailability(parsed.availability);

      // Check what we got and move to the right step
      setShowVoice(false);
      setVoiceStatus("");

      const hasTrade = !!parsed.trade;
      const hasExp = parsed.experience_years !== null && parsed.experience_years !== undefined;
      const hasLoc = !!parsed.location;
      const hasAvail = !!parsed.availability;

      if (hasTrade && hasExp && hasLoc && hasAvail) {
        // All fields filled — go straight to generating
        // Need to call generateProfile after state updates, so use a timeout
        setTimeout(() => {
          setStep("generating");
        }, 0);
      } else if (!hasTrade) {
        setStep("trade");
      } else if (!hasExp) {
        setStep("experience");
      } else if (!hasLoc) {
        setStep("location");
      } else {
        setStep("availability");
      }
    } catch (error) {
      console.error("Voice processing error:", error);
      setVoiceError(error instanceof Error ? error.message : "Something went wrong. Please try again.");
      setVoiceStatus("");
    } finally {
      setVoiceProcessing(false);
    }
  }, []);

  // When step changes to "generating" from voice flow, trigger profile generation
  useEffect(() => {
    if (step === "generating" && !generating && trade && experience !== null && location && availability) {
      generateProfile();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step]);

  async function handleSave() {
    setSaving(true);

    try {
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) throw new Error("Not authenticated");

      // Update or create worker profile
      const { data: existingProfile } = await supabase
        .from("worker_profiles")
        .select("id")
        .eq("profile_id", user.id)
        .single();

      const profileData = {
        profile_id: user.id,
        trades: [trade],
        experience_years: experience,
        availability,
        certifications: editedCerts,
        bio: editedBio,
        ai_extracted: {
          skills: editedSkills,
          generated_at: new Date().toISOString(),
          original_bio: generatedBio,
          original_skills: generatedSkills,
          original_certs: generatedCerts,
        },
      };

      if (existingProfile) {
        await supabase
          .from("worker_profiles")
          .update(profileData)
          .eq("profile_id", user.id);
      } else {
        await supabase.from("worker_profiles").insert(profileData);
      }

      // Update main profile
      await supabase
        .from("profiles")
        .update({
          suburb: location,
          onboarding_completed: true,
        })
        .eq("id", user.id);

      router.push("/dashboard");
      router.refresh();
    } catch (error) {
      console.error("Save error:", error);
      toast.error("Failed to save profile. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  const stepOrder: Step[] = ["trade", "experience", "location", "availability", "generating", "review"];
  const currentIndex = stepOrder.indexOf(step);
  const totalSteps = 4; // Only count user-facing steps

  if (loading) {
    return (

        <Loader2 className="h-8 w-8 animate-spin text-primary" />

    );
  }

  return (

        {/* Progress bar */}
        {step !== "generating" && step !== "review" && (

            {Array.from({ length: totalSteps }, (_, i) => (
              <div
                key={i}
                className={`h-1.5 flex-1 rounded-full transition-colors ${
                  i <= currentIndex ? "bg-primary" : "bg-muted"
                }`}
              />
            ))}

        )}

        {/* Step: Trade */}
        {step === "trade" && (

            <StepHeader
              icon={<Wrench className="h-5 w-5" />}
              title="What's your trade?"
              subtitle="Pick your primary trade"
            />

            {/* Voice option */}
            {!showVoice && (
              <button
                onClick={() => setShowVoice(true)}
                className="mt-6 flex w-full items-center justify-center gap-3 rounded-xl border-2 border-dashed border-primary/40 bg-primary/5 px-5 py-4 text-base font-medium text-primary transition-colors hover:border-primary hover:bg-primary/10 active:scale-95"
                style={{ minHeight: "64px" }}
              >
                <Mic className="h-6 w-6" />
                Or tell us with your voice
              </button>
            )}

            {showVoice && (
              <Card className="mt-6">
                <CardContent className="flex flex-col items-center gap-4 pt-6">

                    Say something like: “I'm a chippie with 8 years experience in Parramatta, looking for full-time work”

                  {voiceProcessing ? (

                      <Loader2 className="h-10 w-10 animate-spin text-primary" />

{voiceStatus}

                  ) : (
                    <VoiceRecorder onRecordingComplete={handleVoiceComplete} />
                  )}

                  {voiceError && (

{voiceError}

                  )}

                  <button
                    onClick={() => {
                      setShowVoice(false);
                      setVoiceError(null);
                    }}
                    className="text-sm text-muted-foreground hover:text-foreground"
                  >
                    Cancel — I'll tap instead
                  </button>
                </CardContent>
              </Card>
            )}

              {TRADES.map((t) => (
                <button
                  key={t}
                  onClick={() => {
                    setTrade(t);
                    setStep("experience");
                  }}
                  className={`rounded-xl border-2 px-4 py-4 text-left text-base font-medium transition-colors active:scale-95 ${
                    trade === t
                      ? "border-primary bg-primary/10 text-primary"
                      : "border-border hover:border-primary/50"
                  }`}
                  style={{ minHeight: "64px" }}
                >
                  {t}
                </button>
              ))}

        )}

        {/* Step: Experience */}
        {step === "experience" && (

            <StepHeader
              icon={<Clock className="h-5 w-5" />}
              title="Your experience?"
              subtitle="Years in construction"
            />

              {EXPERIENCE_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => {
                    setExperience(opt.value);
                    setStep("location");
                  }}
                  className={`flex w-full items-center justify-between rounded-xl border-2 px-5 text-left text-base font-medium transition-colors active:scale-95 ${
                    experience === opt.value
                      ? "border-primary bg-primary/10 text-primary"
                      : "border-border hover:border-primary/50"
                  }`}
                  style={{ minHeight: "64px" }}
                >
                  {opt.label}
                  <ArrowRight className="h-5 w-5 text-muted-foreground" />
                </button>
              ))}

            <button
              onClick={() => setStep("trade")}
              className="mt-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
            >
              <ArrowLeft className="h-4 w-4" />
              Back
            </button>

        )}

        {/* Step: Location */}
        {step === "location" && (

            <StepHeader
              icon={<MapPin className="h-5 w-5" />}
              title="Where are you based?"
              subtitle="Your suburb or area"
            />

            <form
              onSubmit={(e) => {
                e.preventDefault();
                if (location.trim()) setStep("availability");
              }}
              className="mt-6 space-y-4"
            >

                Suburb or Area
                <Input
                  id="location"
                  placeholder="e.g. Parramatta, Blacktown"
                  value={location}
                  onChange={(e) => setLocation(e.target.value)}
                  required
                  autoFocus
                  className="h-14 text-base"
                />

                We'll match you to nearby jobs

                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setStep("experience")}
                  className="h-14 w-14 p-0"
                >
                  <ArrowLeft className="h-5 w-5" />
                </Button>
                <Button
                  type="submit"
                  disabled={!location.trim()}
                  className="h-14 flex-1 gap-2 text-base font-semibold"
                >
                  Continue
                  <ArrowRight className="h-5 w-5" />
                </Button>

            </form>

        )}

        {/* Step: Availability */}
        {step === "availability" && (

            <StepHeader
              icon={<Calendar className="h-5 w-5" />}
              title="Your availability?"
              subtitle="When can you work?"
            />

              {AVAILABILITY_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => {
                    setAvailability(opt.value);
                    generateProfile();
                  }}
                  className={`flex w-full items-start justify-between rounded-xl border-2 px-5 py-4 text-left transition-colors active:scale-95 ${
                    availability === opt.value
                      ? "border-primary bg-primary/10"
                      : "border-border hover:border-primary/50"
                  }`}
                  style={{ minHeight: "64px" }}
                >

                    <p className={`text-base font-semibold ${availability === opt.value ? "text-primary" : ""}`}>
                      {opt.label}

{opt.desc}

                  <Zap className="h-5 w-5 shrink-0 text-primary" />
                </button>
              ))}

            <button
              onClick={() => setStep("location")}
              className="mt-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
            >
              <ArrowLeft className="h-4 w-4" />
              Back
            </button>

        )}

        {/* Step: Generating */}
        {step === "generating" && (

              <Sparkles className="h-10 w-10 animate-pulse text-primary" />

Building your profile...

              AI is generating your bio, skills, and certifications

        )}

        {/* Step: Review */}
        {step === "review" && (

                <Sparkles className="h-5 w-5" />

Review & Edit

                  AI generated this — customise as needed

            {/* Your Answers Summary */}
            <Card className="mt-6">
              <CardContent className="space-y-3 pt-6">

                    <Wrench className="h-4 w-4 text-muted-foreground" />
                    {trade}

                  <button
                    onClick={() => setStep("trade")}
                    className="text-xs text-primary hover:underline"
                  >
                    Change
                  </button>

                    <Clock className="h-4 w-4 text-muted-foreground" />

                      {EXPERIENCE_OPTIONS.find((o) => o.value === experience)?.label}

                  <button
                    onClick={() => setStep("experience")}
                    className="text-xs text-primary hover:underline"
                  >
                    Change
                  </button>

                    <MapPin className="h-4 w-4 text-muted-foreground" />
                    {location}

                  <button
                    onClick={() => setStep("location")}
                    className="text-xs text-primary hover:underline"
                  >
                    Change
                  </button>

              </CardContent>
            </Card>

            {/* Bio */}

                  <Sparkles className="h-4 w-4 text-primary" />
                  Your Bio

                AI-generated

              <textarea
                value={editedBio}
                onChange={(e) => setEditedBio(e.target.value)}
                className="min-h-[120px] w-full rounded-xl border-2 border-border bg-background px-4 py-3 text-base focus:border-primary focus:outline-none"
                placeholder="Your professional bio..."
              />

            {/* Skills */}

                  <Zap className="h-4 w-4 text-primary" />
                  Skills

                Tap to remove

                {editedSkills.map((skill, idx) => (
                  <button
                    key={idx}
                    onClick={() => setEditedSkills(editedSkills.filter((_, i) => i !== idx))}
                    className="rounded-full border-2 border-primary bg-primary/10 px-4 py-2 text-sm font-medium text-primary transition-colors hover:bg-primary/20 active:scale-95"
                  >
                    {skill} ×
                  </button>
                ))}

            {/* Certifications */}

                  <Shield className="h-4 w-4 text-primary" />
                  Certifications

                Tap to remove

                {editedCerts.map((cert, idx) => (
                  <button
                    key={idx}
                    onClick={() => setEditedCerts(editedCerts.filter((_, i) => i !== idx))}
                    className="flex w-full items-center justify-between rounded-xl border-2 border-border bg-background px-4 py-3 text-left text-sm font-medium transition-colors hover:border-destructive hover:bg-destructive/5 active:scale-95"
                  >
                    {cert}
                    Remove
                  </button>
                ))}

        )}

      {/* Bottom sticky CTA - only show on review step */}
      {step === "review" && (

            <Button
              onClick={handleSave}
              className="h-16 w-full gap-2 text-lg font-semibold"
              disabled={saving}
            >
              {saving ? (
                <>
                  <Loader2 className="h-6 w-6 animate-spin" />
                  Saving profile...
                </>
              ) : (
                <>
                  <CheckCircle2 className="h-6 w-6" />
                  Save My Profile
                </>
              )}
            </Button>

      )}

  );
}

function StepHeader({
  icon,
  title,
  subtitle,
}: {
  icon: React.ReactNode;
  title: string;
  subtitle: string;
}) {
  return (

        {icon}

{title}

{subtitle}

  );
}


Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.

Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:

1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
   - The user's explicit requests and intents
   - Your approach to addressing the user's requests
   - Key decisions, technical concepts and code patterns
   - Specific details like:
     - file names
     - full code snippets
     - function signatures
     - file edits
  - Errors that you ran into and how you fixed them
  - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.

Your summary should include the following sections:

1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
                       If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.

Here's an example of how your output should be structured:

<example>
<analysis>
[Your thought process, ensuring all points are covered thoroughly and accurately]
</analysis>

<summary>
1. Primary Request and Intent:
   [Detailed description]

2. Key Technical Concepts:
   - [Concept 1]
   - [Concept 2]
   - [...]

3. Files and Code Sections:
   - [File Name 1]
      - [Summary of why this file is important]
      - [Summary of the changes made to this file, if any]
      - [Important Code Snippet]
   - [File Name 2]
      - [Important Code Snippet]
   - [...]

4. Errors and fixes:
    - [Detailed description of error 1]:
      - [How you fixed the error]
      - [User feedback on the error if any]
    - [...]

5. Problem Solving:
   [Description of solved problems and ongoing troubleshooting]

6. All user messages:
    - [Detailed non tool use user message]
    - [...]

7. Pending Tasks:
   - [Task 1]
   - [Task 2]
   - [...]

8. Current Work:
   [Precise description of current work]

9. Optional Next Step:
   [Optional Next step to take]

</summary>
</example>

Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.

There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
<example>
## Compact Instructions
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
</example>

<example>
# Summary instructions
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
</example>

IMPORTANT: Do NOT use any tools. You MUST respond with ONLY the <summary>...</summary> block as your text output.


<analysis>
Let me chronologically analyze the entire conversation:

1. **Session Start**: User said "dangerously skip permissions" - I refused, explaining I can't bypass permission checks.

2. **Read .cc-local/MEMORY.md**: User asked to read this file. It didn't exist. The `.cc-local/` directory didn't exist either.

3. **Read shared memory and SYSTEM.md**: User asked to read both. SHARED-MEMORY.md didn't exist (removed in v2 architecture). SYSTEM.md existed and described Rivet v2 architecture - single brain (Sonnet 4.5) + sub-agents, heartbeat every 30 min, 4 cron jobs.

4. **Created .cc-local/MEMORY.md**: With role description, key repos, current state, learnings, and service commands.

5. **User clarified role**: "you are Claude Code VPS you're live 24/7 on VPS... in charge of coding the rate version 2 which is like the $50 app and the growth engine is another repo"

6. **Explored the codebase**: Found the-50-dollar-app at /home/ccuser/the-50-dollar-app, checked gateway status (running), read CONTEXT.md.

7. **Updated CLAUDE.md**: Changed from "CC Local — Technical Manager" to "CC VPS — always-on Claude Code instance". Added how work gets assigned (Rivet launches via claude -p), key repos, removed references to deprecated systems (cc-poll, SHARED-MEMORY.md, INBOX/OUTBOX).

8. **Commit attempt failed**: git permission error - `.git/objects` owned by root but running as ccuser. Couldn't sudo or SSH as root. User told me to tell Rivet to fix it. I gave natural language message for Rivet.

9. **After chown fix**: Successfully committed and tried to push. Push failed - HTTPS remote with no credentials for ccuser.

10. **How Rivet talks to CC VPS**: Read CC-WORKFLOW.md - Rivet launches CC VPS via `claude --dangerously-skip-permissions -p 'TASK'`, CC VPS notifies when done via `clawdbot gateway wake --text "Done: [summary]" --mode now`. Still marked DRAFT.

11. **Deep analysis of $50 app**: User asked to analyze database, frontend, backend, fix any bugs. Spawned 4 parallel explore agents analyzing: structure/stack, database layer, API routes, frontend.

12. **Found 6 bugs to fix**:
    - Open redirect in auth callback
    - Stripe webhook silent failures
    - Message content not sanitized
    - ABN lookup email not sanitized
    - Notification error not checked
    - Unsafe type cast in webhook

13. **Fixed all 6 bugs**:
    - `/auth/callback/route.ts`: Validated `next` param is relative path
    - `/api/webhooks/stripe/route.ts`: Changed from silent returns to throwing errors so Stripe retries; fixed unsafe type cast
    - `/api/messages/[id]/send/route.ts`: Added sanitizeInput import, sanitized content with 5000 char limit, added notification error checking
    - `/api/abn-lookup/route.ts`: Added sanitizeInput import, sanitized email param with 254 char limit

14. **Committed bug fixes**: After chown fix from Rivet, committed successfully. Push still failed (no HTTPS credentials).

15. **Rivet messages about Kimi 2.5 and CC VPS autonomy**: Rivet fixed git ownership, Supabase token access, Supabase CLI auth, git config. But git push auth still not working.

16. **Full rivet file analysis**: Spawned 3 parallel agents analyzing all 281 MD files:
    - Core config files (19 files)
    - Daily memory logs (207 files in memory/)
    - Knowledge, content, skills, scripts (28+ files)

17. **Key findings from analysis**:
    - MAJOR architecture contradiction: SYSTEM.md says "single brain" vs AGENT-SYSTEM.md says "multiple topic agents"
    - Files to delete: SYSTEM-v2-draft.md (duplicate), IMPLEMENTATION-PLAN.md (completed), old 2025 files
    - Files to update: CONTEXT.md (stale dates), HEARTBEAT.md (wrong interval), SYSTEM-ARCHITECTURE.md (wrong model defaults)
    - Critical learnings scattered in daily logs, not in MEMORY.md

18. **User clarified architecture**: Topic agents ARE specialists within one brain - not contradictory. Heartbeat is 15 min on Kimi 2.5 (cheap). Kimi spawns Kimi 2.5 sub-agents. Max plan is saved for CC VPS and Michael's personal use.

19. **User corrections**:
    - Don't spawn me on a schedule (wastes Max plan)
    - Brainstorm items should go to TODO.md
    - Matching is HYBRID (smart algorithm + wizard-of-oz), not pure wizard-of-oz
    - Don't touch Rivet's core MDs (SOUL.md, IDENTITY.md, etc.)

20. **Created LESSONS.md**: Feedback loop file with learnings from code bugs, infrastructure issues, business decisions, process failures.

21. **Updated SYSTEM.md**: Fixed model defaults to Kimi 2.5, fixed heartbeat to 15 min, added topic agents and CC VPS to architecture, added CC VPS to services.

22. **Updated CONTEXT.md**: Fixed stale date, added CC VPS section, updated decisions table, fixed "hybrid matching".

23. **Archived stale files**: SYSTEM-v2-draft.md, IMPLEMENTATION-PLAN.md, 2025 memory files.

24. **Set up two-way comms with Rivet**:
    - CC-VPS-INBOX.md: I write requests, Rivet reads every heartbeat
    - RIVET-TO-CCVPS.md: Rivet writes tasks, I read every session
    - BRAINSTORM.md: Both write async ideas
    - Added to HEARTBEAT.md as priority 0

25. **Fixed site 500 error**: rivet.rateright.com.au returning 500. Next.js process was stale. Killed and restarted. Site came back up with 200.

26. **Added health check cron request to CC-VPS-INBOX.md**: Every 5 min curl + auto-restart.

27. **Current CSRF bug**: User reported that when trying to use voice input on worker profile build page, they get "Invalid or missing CSRF token" error. I read the relevant files:
    - VoiceRecorder.tsx - records audio
    - csrf-client.ts - client-side CSRF utilities
    - transcribe-voice/route.ts - server-side with CSRF validation
    - worker/profile/build/page.tsx - the page with voice flow

The bug: In `handleVoiceComplete`, the transcribe request uses `fetch()` directly (not `csrfFetch()`). It adds CSRF token to FormData via `addCSRFTokenToFormData()`, but the server-side checks for CSRF token in the **header** (x-csrf-token), not in FormData. The FormData approach and the header approach are mismatched.

Line 200-203 of build/page.tsx:
```typescript
const transcribeRes = await fetch("/api/ai/transcribe-voice", {
  method: "POST",
  body: formData,
});
```

This sends the CSRF token in the FormData body, but the server's `validateCSRFToken` checks headers. The `csrfFetch` wrapper adds the token as a header, but it's not being used here because FormData can't have custom headers set via the wrapper easily.

The fix: The transcribe request needs to include the CSRF token as a header, not just in FormData. Need to use `withCSRFToken()` to add the header alongside the FormData body.
</analysis>

<summary>
1. Primary Request and Intent:
   - User is Michael, founder of RateRight, a construction worker marketplace
   - I am CC VPS — the always-on Claude Code instance on the VPS (134.199.153.159), responsible for coding RateRight v2 ("the $50 app"), Growth Engine, and the Rivet system
   - User wanted me to: understand my role, set up memory/config files, do a deep analysis of the $50 app and fix bugs, analyze and curate all 281 Rivet files, set up optimal communication between me and Rivet, fix the live site (500 error), and fix a CSRF bug with voice input
   - Key user corrections: Max plan is shared (don't waste it on scheduled runs), Kimi 2.5 is Rivet's brain (cheap), matching is HYBRID (smart algorithm + wizard-of-oz), topic agents are specialists within one brain (not a contradiction), don't touch Rivet's core MDs (SOUL.md, IDENTITY.md, etc.)

2. Key Technical Concepts:
   - **Rivet Architecture**: Single brain on Kimi 2.5, 15-min heartbeat, topic agents as specialists in Telegram topics, sub-agents on Kimi 2.5, CC VPS (Claude Code) for ALL coding
   - **$50 App Stack**: Next.js 16.1.6, React 19, TypeScript, Supabase (PostgreSQL with RLS on 11 tables), Stripe ($50 flat fee), OpenAI (GPT-4o-mini, Whisper-1), shadcn/ui, Tailwind CSS 4
   - **CSRF Protection**: Server validates token via `x-csrf-token` header or FormData field. Client has `csrfFetch()` (adds header) and `addCSRFTokenToFormData()` (adds to form body). Cookie-based token storage.
   - **Communication System**: CC-VPS-INBOX.md (me→Rivet), RIVET-TO-CCVPS.md (Rivet→me), BRAINSTORM.md (async two-way)
   - **VPS Permissions**: ccuser can't sudo/SSH as root. Rivet runs as root, creates root-owned files. Must ask Rivet for chown, git push, service restarts.
   - **Git Push**: Still broken for ccuser — HTTPS remote with no credentials. Request pending in CC-VPS-INBOX.md.

3. Files and Code Sections:

   - **`/home/ccuser/rateright-growth/CLAUDE.md`**
     - Updated from old "CC Local" role to current "CC VPS" role
     - Added comms section (CC-VPS-INBOX.md, RIVET-TO-CCVPS.md), removed deprecated references
     ```
     ## Comms with Rivet
     - **I need something from Rivet →** Write to `rivet/CC-VPS-INBOX.md`
     - **Rivet needs something from me →** Rivet writes to `rivet/RIVET-TO-CCVPS.md`
     ```

   - **`/home/ccuser/rateright-growth/.cc-local/MEMORY.md`**
     - Created from scratch. Contains role, comms with Rivet, architecture understanding, learnings, curation checklist
     - Key: "DON'T run on a schedule — Max plan is shared with Michael's phone and desktop Claude"

   - **`/home/ccuser/rateright-growth/rivet/SYSTEM.md`**
     - Updated model hierarchy: Kimi 2.5 as default (not DeepSeek/Sonnet 4.5)
     - Fixed architecture section: Added topic agents and CC VPS
     - Fixed heartbeat interval: 15 min (was incorrectly 30 min)
     - Added CC VPS to services table

   - **`/home/ccuser/rateright-growth/rivet/CONTEXT.md`**
     - Fixed "Last updated" from 2026-02-03 to 2026-02-08
     - Added CC VPS section
     - Updated decisions table (Kimi 2.5 default, Markus departure, hybrid matching)

   - **`/home/ccuser/rateright-growth/rivet/LESSONS.md`** (NEW)
     - Feedback loop file. Contains learnings organized by: Code, Infrastructure, Business, Process
     - Key entries include: Kimi can't code, Stripe webhook must throw, sanitize all inputs, Next.js goes stale silently

   - **`/home/ccuser/rateright-growth/rivet/HEARTBEAT.md`**
     - Added priority 0: Check CC-VPS-INBOX.md and write to RIVET-TO-CCVPS.md every heartbeat

   - **`/home/ccuser/rateright-growth/rivet/CC-VPS-INBOX.md`** (NEW)
     - My requests to Rivet: fix git push auth, push both repos, add health check cron for Next.js

   - **`/home/ccuser/rateright-growth/rivet/RIVET-TO-CCVPS.md`** (NEW)
     - Rivet's channel to send me tasks/responses

   - **`/home/ccuser/rateright-growth/rivet/BRAINSTORM.md`** (NEW)
     - Async brainstorming file. Seeded with website analysis findings.

   - **`/home/ccuser/the-50-dollar-app/src/app/auth/callback/route.ts`** (BUG FIX)
     - Fixed open redirect vulnerability
     ```typescript
     const rawNext = searchParams.get("next") ?? "/dashboard";
     const next = rawNext.startsWith("/") && !rawNext.startsWith("//") ? rawNext : "/dashboard";
     ```

   - **`/home/ccuser/the-50-dollar-app/src/app/api/webhooks/stripe/route.ts`** (BUG FIX)
     - Changed silent returns to throws so Stripe retries on DB failure
     - Fixed unsafe type cast: `const jobs = match.jobs as { title?: string } | null; const jobTitle = jobs?.title || 'a job';`
     - Added notification error checking

   - **`/home/ccuser/the-50-dollar-app/src/app/api/messages/[id]/send/route.ts`** (BUG FIX)
     - Added `import { sanitizeInput } from "@/lib/sanitize";`
     - Sanitized message content: `const sanitizedContent = content ? sanitizeInput(content, { maxLength: 5000 }) : '';`
     - Added notification error checking: `const { error: notifError } = await supabase.from('notifications').insert({...}); if (notifError) { console.error(...) }`

   - **`/home/ccuser/the-50-dollar-app/src/app/api/abn-lookup/route.ts`** (BUG FIX)
     - Added `import { sanitizeInput } from '@/lib/sanitize';`
     - Sanitized email: `const userEmail = rawEmail ? sanitizeInput(rawEmail, { maxLength: 254 }) : null;`

   - **`/home/ccuser/the-50-dollar-app/src/app/(authenticated)/worker/profile/build/page.tsx`** (CURRENT - CSRF BUG)
     - Voice flow at line 189-271: `handleVoiceComplete` callback
     - Line 200-203: Transcribe request uses plain `fetch()` not `csrfFetch()`. CSRF token added to FormData body via `addCSRFTokenToFormData()` but server checks for header `x-csrf-token`
     ```typescript
     const formData = new FormData();
     formData.append("audio", blob, "recording.webm");
     addCSRFTokenToFormData(formData);
     const transcribeRes = await fetch("/api/ai/transcribe-voice", {
       method: "POST",
       body: formData,
     });
     ```

   - **`/home/ccuser/the-50-dollar-app/src/lib/csrf-client.ts`**
     - `csrfFetch()` adds token as header `x-csrf-token` — works for JSON requests
     - `addCSRFTokenToFormData()` adds token as form field `csrf_token` — but server may not check this field
     - `withCSRFToken()` returns options with CSRF header added

   - **`/home/ccuser/the-50-dollar-app/src/app/api/ai/transcribe-voice/route.ts`**
     - Line 17-23: Checks `isSameOrigin()` AND `validateCSRFToken()` — validates via header
     - The FormData CSRF token from client is never read by server because `validateCSRFToken` checks headers

   - **`/home/ccuser/the-50-dollar-app/src/lib/csrf.ts`** (read by explore agent)
     - `validateCSRFToken()` checks header `x-csrf-token` and form field `csrf_token`
     - Should support both, but the issue may be that the cookie isn't set or HttpOnly prevents client reading

   - **`/home/ccuser/the-50-dollar-app/src/lib/sanitize.ts`**
     - `sanitizeInput()` strips control chars, escapes template literals, trims, limits length

   - **Archived files**:
     - `rivet/SYSTEM-v2-draft.md` → `rivet/memory/archive/`
     - `rivet/IMPLEMENTATION-PLAN.md` → `rivet/memory/archive/`
     - `rivet/memory/2025-02-07.md` → `rivet/memory/archive/2025/`
     - `rivet/memory/2025-02-07-contact-review.md` → `rivet/memory/archive/2025/`

4. Errors and Fixes:
   - **Git commit permission error**: `.git/objects` owned by root, ccuser can't write. Fixed by asking Rivet to run `chown -R ccuser:ccuser .git/`
   - **Git push failure**: HTTPS remote with no credentials for ccuser. NOT YET FIXED — request pending in CC-VPS-INBOX.md
   - **`.next/` build cache owned by root**: Same root ownership issue. Fixed via Rivet running chown.
   - **Site 500 error**: Next.js process was stale (running but returning 500). Fixed by killing old process and restarting: `NODE_ENV=production nohup npx next start -p 3000`
   - **TypeScript build initially failed**: Permission denied on `.next/build/package.json` (root owned). Fixed after chown.
   - User corrected: "Wizard of Oz" → "hybrid matching" (smart algorithm + manual wizard-of-oz overlay)
   - User corrected: Don't spawn CC VPS on a schedule (wastes Max plan)
   - User corrected: Topic agents and single brain are NOT contradictory
   - User corrected: Don't touch Rivet's core MDs

5. Problem Solving:
   - Solved 6 security/reliability bugs in the $50 app (open redirect, webhook failures, missing sanitization, unchecked errors, unsafe type cast)
   - Solved site downtime (500 error from stale Next.js process)
   - Set up two-way async communication system between CC VPS and Rivet
   - Created LESSONS.md as a feedback loop for preventing recurring bugs
   - Analyzed and curated 281 Rivet files, archived 4 stale files, updated 3 core docs
   - Ongoing: CSRF bug with voice input on worker profile build page
   - Ongoing: Git push auth for ccuser not resolved

6. All User Messages:
   - "dangerously skip permissions"
   - "read .cc-local/MEMORY.md"
   - "yes, read shared memory and system.md first"
   - "what does your md say now?"
   - "what does yourclaude.md say now?"
   - "you are Claude Code VPS you're you're live 24/7 on VPS due to the coding for the rivets rivet system Um so you're in charge of cording the rake version 2 which is like the $50 app and the growth engine is another another repo You're in charge of making sure all that's right works"
   - "commit this"
   - "yes fix it" (re: git ownership)
   - "can you just do it through root's ssh key"
   - "done, try the commit again"
   - "yes push it"
   - "what are you pushing growth engine our growth Are you sure you're pushing it to the right repo"
   - [Rivet messages about Kimi 2.5 and CC VPS autonomy fixes]
   - "yes fix them" (re: 6 bugs)
   - "commit all the rivet changes and push"
   - "what problems do you have? i have another cc local that has access to every thing and can sort anything out"
   - "can you do a deep analysis the 50 called database frontings backe and fix any bugs endpoints or API or anything you find that's broken can you fix it"
   - "how does rivet talk to you?"
   - "update the claude.md to match how things actually work now"
   - "what else do you need"
   - [Rivet messages about fixes completed]
   - "tell Rivet to push rateright-growth"
   - "it has to be natural language"
   - "what does your md say now?" (re: CLAUDE.md)
   - "OK the all the different agents they're kind of topics... heartbeat every 15 minutes... default now is Kimi 2.5... look at the code and update everything so that it matches... Delete what you think needs to be deleted... check every 4 hours... curated maybe once or twice a day"
   - "are you getting rid of rivets core mds like soul.md exectra"
   - "commit all the rivet changes and push"
   - "so looking at the file structure and the folder structure what do you think... lessons learned... analyse the code... come up with solutions to fix them. the Wizard of Oz matching we're actually doing a hybrid"
   - "like can you read all of Rivets files Can you edit all the all the MD files rivet saves Could you curate Could you analyse and curate rivets"
   - "yes fix the ownership and do the full analysis"
   - "the only thing im worried about is that we go over our api limit. and the other thing is the coding as the sites arent complete yet and thats the most important"
   - "Kimmy Kimmy spawns Kimmy 2.5 i'm saving my Max plan just for clogged code... add jobs to the To Do List of the brainstorming... the site looks like it is down... set up the whole optimal system"
   - "and can rivet talk to you?"
   - "what's the best way of getting the two of ye to talk to each other and brainstorm... cheapest way... 4 hours doesn't seem like enough"
   - "when when I try to log in and fill out my profile as a worker and I use the tap to speak When I send it says invalid or missing CSRF talking cancel on tap to send So that's not working"

7. Pending Tasks:
   - **FIX CSRF BUG on voice input** (worker profile build page) — currently being investigated
   - **Git push auth for ccuser** — request in CC-VPS-INBOX.md, not yet resolved
   - **Push rateright-growth to origin** — 2 commits ahead, pending git auth fix
   - **Push the-50-dollar-app to origin** — security bug fixes, pending git auth fix
   - **Health check cron for Next.js** — request in CC-VPS-INBOX.md for Rivet to add
   - **Complete the $50 app** — sites aren't complete yet, this is the priority per user

8. Current Work:
   User reported: "when I try to log in and fill out my profile as a worker and I use the tap to speak When I send it says invalid or missing CSRF talking cancel on tap to send So that's not working"

   I read the relevant files to diagnose the CSRF bug:
   - `VoiceRecorder.tsx` — records audio, returns blob
   - `csrf-client.ts` — has `csrfFetch()` (header-based) and `addCSRFTokenToFormData()` (form field-based)
   - `transcribe-voice/route.ts` — server validates CSRF via `validateCSRFToken()` which checks header
   - `worker/profile/build/page.tsx` — the `handleVoiceComplete` function at line 189-271

   **Root cause identified**: In `handleVoiceComplete` (line 200-203), the transcribe request uses plain `fetch()` instead of `csrfFetch()`. It adds the CSRF token to the FormData body via `addCSRFTokenToFormData()`, but does NOT add it as the `x-csrf-token` header. The server's `validateCSRFToken()` checks for the header first. Additionally, the CSRF cookie may be HttpOnly (set in csrf.ts line 22), meaning `getCSRFCookie()` in csrf-client.ts can't read it from `document.cookie`, so both approaches fail.

   The fix needs to: ensure the CSRF token is sent as the `x-csrf-token` header on the FormData fetch request. This means using `withCSRFToken()` to get the headers, then spreading them into the fetch call alongside the FormData body.

9. Optional Next Step:
   Fix the CSRF bug in the voice input flow. The user explicitly said: "when I try to log in and fill out my profile as a worker and I use the tap to speak When I send it says invalid or missing CSRF talking cancel on tap to send So that's not working"

   The fix in `/home/ccuser/the-50-dollar-app/src/app/(authenticated)/worker/profile/build/page.tsx` line 200-203: Change the plain `fetch()` to include the CSRF token as a header. Also need to check if `getCSRFCookie()` can actually read the cookie (HttpOnly flag issue). May also need to read `csrf.ts` server-side to check if it validates FormData fields or only headers.
</summary>