# ============================================================
# Multimodal Semiotic Strategies in Cross-Border E-Commerce
# Statistical Analysis and Figure Generation
# ============================================================
# This R script reproduces all statistical analyses and figures
# reported in the accompanying manuscript.
#
# It is provided as supplementary material to facilitate
# transparency and reproducibility of the reported analyses.
# ============================================================

# --- 0. Setup ------------------------------------------------

# Install packages if needed (uncomment as necessary)
# install.packages(c("readxl", "tidyverse", "vcd", "DescTools", "irr", "ggplot2", "scales", "RColorBrewer"))

library(readxl)
library(tidyverse)
library(vcd)
library(DescTools)
library(ggplot2)
library(scales)

# Set global ggplot theme (APA-like)
theme_apa <- theme_classic(base_size = 12, base_family = "serif") +
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),
    axis.title = element_text(size = 11),
    axis.text = element_text(size = 10),
    legend.title = element_blank(),
    legend.position = "top",
    panel.grid = element_blank()
  )
theme_set(theme_apa)

# --- 1. Load Data --------------------------------------------

df <- read_excel("Supplementary_Dataset.xlsx")

# Ensure Language_Strategy "NA" is treated as a string, not missing
df$Language_Strategy[is.na(df$Language_Strategy)] <- "NA_strategy"
# If read correctly, it should already be "NA" as text.
# Let's verify:
cat("=== Data Overview ===\n")
cat("Rows:", nrow(df), "\n")
cat("Columns:", ncol(df), "\n\n")

cat("Language Strategy distribution:\n")
print(table(df$Language_Strategy))

cat("\nCategory distribution:\n")
print(table(df$Category))


# --- 2. Descriptive Statistics --------------------------------

cat("\n\n========================================\n")
cat("DESCRIPTIVE STATISTICS\n")
cat("========================================\n\n")

# 2a. Language strategy overall
cat("--- Language Strategy (Overall) ---\n")
lang_tab <- table(df$Language_Strategy)
lang_pct <- prop.table(lang_tab) * 100
print(data.frame(
  Strategy = names(lang_tab),
  n = as.integer(lang_tab),
  Percent = round(lang_pct, 1)
))

# 2b. Language strategy by category
cat("\n--- Language Strategy by Category ---\n")
lang_cat <- table(df$Category, df$Language_Strategy)
lang_cat_pct <- prop.table(lang_cat, margin = 1) * 100
print(lang_cat)
cat("\nRow percentages:\n")
print(round(lang_cat_pct, 1))

# 2c. Scene type by market
cat("\n--- Scene Type by Market ---\n")
scene_cn <- table(df$Scene_CN)
scene_us <- table(df$Scene_US)
scene_combined <- data.frame(
  Scene = c("Chinese-style", "Neutral", "Western-style"),
  CN_n = as.integer(scene_cn[c("Chinese-style", "Neutral", "Western-style")]),
  CN_pct = round(as.numeric(prop.table(scene_cn)[c("Chinese-style", "Neutral", "Western-style")]) * 100, 1),
  US_n = as.integer(scene_us[c("Chinese-style", "Neutral", "Western-style")]),
  US_pct = round(as.numeric(prop.table(scene_us)[c("Chinese-style", "Neutral", "Western-style")]) * 100, 1)
)
print(scene_combined)

# 2d. Cultural symbols by market
cat("\n--- Cultural Symbols by Market ---\n")
sym_cn <- table(df$Cultural_Symbol_CN)
sym_us <- table(df$Cultural_Symbol_US)
cat("CN: Present =", sym_cn["Present"], "(", round(sym_cn["Present"]/300*100, 1), "%)\n")
cat("US: Present =", sym_us["Present"], "(", round(sym_us["Present"]/300*100, 1), "%)\n")

# 2e. Image-text by market
cat("\n--- Image-Text Relation by Market ---\n")
it_cn <- table(df$ImageText_CN)
it_us <- table(df$ImageText_US)
cat("CN: Extension =", it_cn["Extension"], "(", round(it_cn["Extension"]/300*100, 1), "%)\n")
cat("US: Extension =", it_us["Extension"], "(", round(it_us["Extension"]/300*100, 1), "%)\n")


# --- 3. Chi-Square Tests --------------------------------------

cat("\n\n========================================\n")
cat("CHI-SQUARE ANALYSES\n")
cat("========================================\n\n")

# Helper function for APA-formatted chi-square output
report_chi <- function(label, ct) {
  test <- chisq.test(ct)
  n <- sum(ct)
  k <- min(dim(ct))
  v <- CramerV(ct)
  cat(label, "\n")
  cat(sprintf("  X2(%d, N = %d) = %.2f, p = %s, Cramer's V = %.2f\n",
              test$parameter, n, test$statistic,
              ifelse(test$p.value < .001, "< .001", sprintf("%.3f", test$p.value)),
              v))
  cat("  Standardized residuals:\n")
  print(round(test$stdres, 2))
  cat("\n")
  return(test)
}

# 3a. Language Strategy x Category
cat("--- Test 1: Language Strategy x Category ---\n")
ct_lang <- table(df$Category, df$Language_Strategy)
test1 <- report_chi("Language Strategy x Product Category", ct_lang)

# 3b. Scene Type x Market
cat("--- Test 2: Scene Type x Market ---\n")
scene_long <- data.frame(
  Scene = c(df$Scene_CN, df$Scene_US),
  Market = rep(c("CN", "US"), each = 300)
)
ct_scene <- table(scene_long$Market, scene_long$Scene)
test2 <- report_chi("Scene Type x Market", ct_scene)

# 3c. Cultural Symbols x Market
cat("--- Test 3: Cultural Symbols x Market ---\n")
sym_long <- data.frame(
  Symbol = c(df$Cultural_Symbol_CN, df$Cultural_Symbol_US),
  Market = rep(c("CN", "US"), each = 300)
)
ct_sym <- table(sym_long$Market, sym_long$Symbol)
test3 <- report_chi("Cultural Symbols x Market", ct_sym)

# 3d. Image-Text x Market
cat("--- Test 4: Image-Text Relation x Market ---\n")
it_long <- data.frame(
  Relation = c(df$ImageText_CN, df$ImageText_US),
  Market = rep(c("CN", "US"), each = 300)
)
ct_it <- table(it_long$Market, it_long$Relation)
test4 <- report_chi("Image-Text Relation x Market", ct_it)

# 3e. Scene x Category (CN)
cat("--- Test 5: Scene x Category (CN Market) ---\n")
ct_scene_cn <- table(df$Category, df$Scene_CN)
test5 <- report_chi("Scene Type x Category (CN)", ct_scene_cn)

# 3f. Scene x Category (US)
cat("--- Test 6: Scene x Category (US Market) ---\n")
ct_scene_us <- table(df$Category, df$Scene_US)
test6 <- report_chi("Scene Type x Category (US)", ct_scene_us)


# --- 4. Summary Table ----------------------------------------

cat("\n\n========================================\n")
cat("SUMMARY TABLE (Table 3 in manuscript)\n")
cat("========================================\n\n")

summary_df <- data.frame(
  Comparison = c("Language x Category", "Scene x Market",
                 "Symbol x Market", "Image-Text x Market"),
  Chi_sq = c(test1$statistic, test2$statistic,
             test3$statistic, test4$statistic),
  df = c(test1$parameter, test2$parameter,
         test3$parameter, test4$parameter),
  N = c(300, 600, 600, 600),
  p = c(test1$p.value, test2$p.value,
        test3$p.value, test4$p.value),
  V = c(CramerV(ct_lang), CramerV(ct_scene),
        CramerV(ct_sym), CramerV(ct_it))
)
summary_df$Effect <- ifelse(summary_df$V >= .50, "Large",
                     ifelse(summary_df$V >= .30, "Medium",
                     ifelse(summary_df$V >= .10, "Small", "Negligible")))
print(summary_df, digits = 3)


# --- 5. Figures -----------------------------------------------

cat("\n\nGenerating figures...\n")

# Color palette
col_dark <- "#2c3e50"
col_mid <- "#7f8c8d"
col_light <- "#bdc3c7"
col_cn <- "#c0392b"
col_us <- "#2c3e50"

# Category order
cat_order <- c("Festive Decoration", "Jewelry/Pendants", "Hair Accessories",
               "Daily Necessities/Apparel", "Others")
cat_labels <- c("Festive\nDecoration", "Jewelry/\nPendants", "Hair\nAccessories",
                "Daily Necessities/\nApparel", "Others")

# 5a. Figure 1: Language Strategy by Category (Grouped Bar)
lang_plot_df <- df %>%
  mutate(Category = factor(Category, levels = cat_order)) %>%
  count(Category, Language_Strategy) %>%
  group_by(Category) %>%
  mutate(pct = n / sum(n) * 100) %>%
  ungroup() %>%
  mutate(Language_Strategy = factor(Language_Strategy,
                                    levels = c("Foreignization", "Domestication", "NA")))

p1 <- ggplot(lang_plot_df, aes(x = Category, y = pct, fill = Language_Strategy)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  geom_text(aes(label = sprintf("%.1f%%", pct)),
            position = position_dodge(width = 0.8), vjust = -0.5, size = 3) +
  scale_fill_manual(values = c(col_dark, col_mid, col_light)) +
  scale_x_discrete(labels = cat_labels) +
  labs(x = "Product Category", y = "Percentage (%)") +
  ylim(0, 100) +
  theme(legend.position = "top")

ggsave("fig1_language_strategy.png", p1, width = 8, height = 5, dpi = 300)

# 5b. Figure 2: Heatmap of Standardized Residuals
stdres_df <- as.data.frame(as.table(round(test1$stdres, 2)))
names(stdres_df) <- c("Category", "Strategy", "Residual")
stdres_df$Category <- factor(stdres_df$Category, levels = rev(cat_order))

p2 <- ggplot(stdres_df, aes(x = Strategy, y = Category, fill = Residual)) +
  geom_tile(color = "white", linewidth = 0.5) +
  geom_text(aes(label = sprintf("%.2f", Residual)), size = 4) +
  scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b",
                       midpoint = 0, name = "Standardized\nResidual") +
  labs(x = "Language Strategy", y = "Product Category") +
  theme(axis.text.y = element_text(size = 10))

ggsave("fig2_heatmap.png", p2, width = 7, height = 5, dpi = 300)

# 5c. Figure 3: Scene Type Comparison (CN vs US)
scene_plot_df <- data.frame(
  Scene = rep(c("Chinese-style", "Neutral", "Western-style"), 2),
  Market = rep(c("CN Market", "US Market"), each = 3),
  pct = c(
    sum(df$Scene_CN == "Chinese-style") / 300 * 100,
    sum(df$Scene_CN == "Neutral") / 300 * 100,
    sum(df$Scene_CN == "Western-style") / 300 * 100,
    sum(df$Scene_US == "Chinese-style") / 300 * 100,
    sum(df$Scene_US == "Neutral") / 300 * 100,
    sum(df$Scene_US == "Western-style") / 300 * 100
  )
)
scene_plot_df$Scene <- factor(scene_plot_df$Scene,
                               levels = c("Chinese-style", "Neutral", "Western-style"))

p3 <- ggplot(scene_plot_df, aes(x = Scene, y = pct, fill = Market)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  geom_text(aes(label = sprintf("%.1f%%", pct)),
            position = position_dodge(width = 0.7), vjust = -0.5, size = 3.5) +
  scale_fill_manual(values = c(col_cn, col_us)) +
  labs(x = "Scene Type", y = "Percentage (%)") +
  ylim(0, 95) +
  theme(legend.position = "top")

ggsave("fig3_scene_comparison.png", p3, width = 6, height = 5, dpi = 300)

# 5d. Figure 4: Cultural Symbol Retention by Category
sym_plot_df <- df %>%
  mutate(Category = factor(Category, levels = cat_order)) %>%
  group_by(Category) %>%
  summarise(
    CN = mean(Cultural_Symbol_CN == "Present") * 100,
    US = mean(Cultural_Symbol_US == "Present") * 100
  ) %>%
  pivot_longer(cols = c(CN, US), names_to = "Market", values_to = "pct") %>%
  mutate(Market = ifelse(Market == "CN", "CN Market", "US Market"))

p4 <- ggplot(sym_plot_df, aes(x = Category, y = pct, fill = Market)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  geom_text(aes(label = sprintf("%.0f%%", pct)),
            position = position_dodge(width = 0.7), vjust = -0.5, size = 3) +
  scale_fill_manual(values = c(col_cn, col_us)) +
  scale_x_discrete(labels = cat_labels) +
  labs(x = "Product Category", y = "Symbol Retention Rate (%)") +
  ylim(0, 100) +
  theme(legend.position = "top")

ggsave("fig4_symbols.png", p4, width = 7, height = 5, dpi = 300)

# 5e. Figure 5: Image-Text Relation Comparison
it_plot_df <- data.frame(
  Relation = rep(c("Extension", "Elaboration"), 2),
  Market = rep(c("CN Market", "US Market"), each = 2),
  pct = c(
    sum(df$ImageText_CN == "Extension") / 300 * 100,
    sum(df$ImageText_CN == "Elaboration") / 300 * 100,
    sum(df$ImageText_US == "Extension") / 300 * 100,
    sum(df$ImageText_US == "Elaboration") / 300 * 100
  )
)

p5 <- ggplot(it_plot_df, aes(x = Relation, y = pct, fill = Market)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  geom_text(aes(label = sprintf("%.1f%%", pct)),
            position = position_dodge(width = 0.7), vjust = -0.5, size = 3.5) +
  scale_fill_manual(values = c(col_cn, col_us)) +
  labs(x = "Image-Text Relation", y = "Percentage (%)") +
  ylim(0, 95) +
  theme(legend.position = "top")

ggsave("fig5_imagetext.png", p5, width = 5, height = 5, dpi = 300)

cat("\nAll figures saved as PNG files (300 dpi).\n")
cat("Done.\n")
